Combining 2 Arrays(of equal or different dimensions)

17 ビュー (過去 30 日間)
Ahmed Khalifa
Ahmed Khalifa 2016 年 5 月 12 日
編集済み: Weird Rando 2016 年 5 月 13 日
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

採用された回答

Weird Rando
Weird Rando 2016 年 5 月 12 日
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 件のコメント
Weird Rando
Weird Rando 2016 年 5 月 12 日
編集済み: Weird Rando 2016 年 5 月 13 日
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 2016 年 5 月 13 日
編集済み: Weird Rando 2016 年 5 月 13 日
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) = [];

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by