How to generate an array alternating the values of two others?
Show older comments
So, I have two arrays (I made them simple for the example)
A = [1 2 3 4 5 6]; B = [10 20 30 40 50 60 70 80 90 100 110 120 130 140 150];
The array I wish to generate is [1 10 2 20 3 30 4 40 5 50 6 60 1 70 2 80 3 90 ...]
Any idea of how to proceed? For now, I'm trying on something like this:
Sequence = []; for i = 1: length(B) j=% ??? range 1:length(A) i=1 j=1; ... i=7 j=1; i=8 j=2; ... 1=n j=??? Sequence = [Sequence A(1,j)]; Sequence = [Sequence B(1,i)]; end
Answers (3)
Jos (10584)
on 22 May 2014
A = [1 2 3 4 5 6];
B = [10 20 30 40 50 60 70 80 90 100 110 120 130 140 150];
% in steps
N = max(numel(A),numel(B))
ia = 1+rem(0:N-1, numel(A))
ib = 1+rem(0:N-1, numel(B))
C = [A(ia) ; B(ib)]
C = reshape(C,1,[])
% in a one-liner
C2 = reshape([A(1+rem(0:max(numel(A),numel(B))-1, numel(A))) ; B(1+rem(0:max(numel(A),numel(B))-1, numel(B)))],1,[])
1 Comment
Andrei Bobrov
on 22 May 2014
+1
George Papazafeiropoulos
on 22 May 2014
Edited: George Papazafeiropoulos
on 22 May 2014
1 vote
A = [1 2 3 4 5 6];
B = [10 20 30 40 50 60 70 80 90 100 110 120 130 140 150];
M1=[A,A,A(1:3)];
M2=B;
M=[M1;M2];
Sequence=M(:)'
Andrei Bobrov
on 22 May 2014
out0 = [A(rem(0:numel(B)-1,numel(A))+1);B];
out = out0(:)';
Categories
Find more on Creating and Concatenating Matrices 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!