Combining 2 Arrays(of equal or different dimensions)

25 views (last 30 days)
Hello, I have hit a wall while doing my ex-homework so I can prepare for my exam.Anyways, here it goes:
Assume that you have two vectors named A2 and B2 of different lengths. Create a vector C2 that combines A2 and B2. In addition, if you run out of elements in one of the vectors, C2 contains the elements remaining from the longer vector. Example: if A2 = [1, 2, 3, 4, 5, 6] and B2 = [10, 20, 30], then C2 = [1, 10, 2, 20, 3, 30, 4, 5, 6] if A2 = [1, 2, 3] and B2 = [10, 20, 30, 40, 50], then C2 = [1, 10, 2, 20, 3, 30, 40, 50]
Also there is this second one, Write a MATLAB program that takes two 2D arrays (they may be of different dimensions) and extracts them into 1D array. Example: If A= [1 2 3; 4 5 6; 3 2 5] and B= [4 5; 1 2; 3 9] Output= [1 2 3 4 5 4 5 6 1 2 3 2 5 3 9] If A= [1 2 3; 4 5 6] and B= [4 5; 1 2; 3 9] Output= [1 2 3 4 5 4 5 6 1 2 3 9]
I would love it if someone is capable of helping me I have failed to solve it no matter how hard I tried. Union function didnt work aswell as there is duplicates in the output array. Thanks

Accepted Answer

Weird Rando
Weird Rando on 12 May 2016
First Exercise: If we create C2 that is an array of zeros which has double the length of A2 and B2 combine. We can space A2 and B2 every 2 element apart and then remove the 0 inside the array.
% creating the C2 array of zeros which has double the length of A2 and B2 combine.
lenA2 = length(A2)*2;
lenB2 = length(B2)*2;
C2 = zeros(1,(lenA2 + lenB2));
% place A2 and B2 in every 2nd element after the starting point
C2(1:2:lenA2) = A2;
C2(2:2:lenB2) = B2;
% removes 0 in the array
C2(C2 == 0) = [];
  3 Comments
Weird Rando
Weird Rando on 12 May 2016
Edited: Weird Rando on 13 May 2016
I was lazy to find which array was longer, so I just double the length A2 and B2 just so it fits in C2. I could of done an if statement with a for loop.
Weird Rando
Weird Rando on 13 May 2016
Edited: Weird Rando on 13 May 2016
2nd part:
[Arow Acol] = size(A);
[Brow Bcol] = size(B);
temp = zeros(Arow+Brow,Acol+Bcol);
temp(1:Arow,1:Acol) = A;
temp(1:Brow,1+Acol:Bcol+Acol) = B; %offset column by Acol
Output = []; %initalise Output for the for loop
nloop = size(temp,1);
for ii = 1:nloop
Output = [Output temp(ii,:)]
end
Output(Output == 0) = [];

Sign in to comment.

More Answers (0)

Categories

Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!