Lets have two arrays of same length, A = [2 4 6 8 10], B = [5 8 3 7 2], I want to know how to have a resultant array which will contain, result = [2 5 4 8 6 3 8 7 10 2]; If the lengths are different, suppose, A = [2 4 6 8 10], B = [5 8 3], so how will I get the result as [2 5 4 8 6 3 8 10];

 Accepted Answer

Birdman
Birdman on 29 Mar 2018
Edited: Birdman on 29 Mar 2018
Consider A has more element than B:
A=2:2:10
B=[5 8 3]
result=zeros(1,numel(A)+numel(B));
Dif=2*numel(B);
dif=numel(A)-numel(B);
result(end:-1:Dif+1)=A(end:-1:numel(A)-dif+1);
A(end:-1:numel(A)-dif+1)=[];
result(1:2:Dif-1)=A;
result(result==0)=B

More Answers (1)

Stephen23
Stephen23 on 29 Mar 2018
Edited: Stephen23 on 29 Mar 2018
Faster, much simpler code, uses less memory, creates only one intermediate variable (a scalar value), and works regardless of which vector is longer. For two row vectors A and B, all you need is:
>> A = [2,4,6,8,10];
>> B = [5,8,3];
>> N = min(numel(A),numel(B));
>> C = [reshape([A(1:N);B(1:N)],1,[]),A(N+1:end),B(N+1:end)]
C =
2 5 4 8 6 3 8 10

1 Comment

Birdman
Birdman on 29 Mar 2018
Edited: Birdman on 29 Mar 2018
Yup, deserved an upvote. But at least mine does not involve a loop, improvement comparing to my beginner time ;-)

Sign in to comment.

Categories

Asked:

on 29 Mar 2018

Edited:

on 29 Mar 2018

Community Treasure Hunt

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

Start Hunting!