How to generate an array alternating the values of two others?

13 vues (au cours des 30 derniers jours)
Baptiste
Baptiste le 22 Mai 2014
Commenté : Andrei Bobrov le 22 Mai 2014
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

Réponses (3)

Jos (10584)
Jos (10584) le 22 Mai 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,[])

George Papazafeiropoulos
George Papazafeiropoulos le 22 Mai 2014
Modifié(e) : George Papazafeiropoulos le 22 Mai 2014
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
Andrei Bobrov le 22 Mai 2014
out0 = [A(rem(0:numel(B)-1,numel(A))+1);B];
out = out0(:)';

Catégories

En savoir plus sur Data Import from MATLAB dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by