Combining 2 Arrays(of equal or different dimensions)

조회 수: 30 (최근 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 CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by