How can I mix two arrays?
11 次查看（过去 30 天）
Alex Strongholm ，2015-1-15
Given A=[1 3 5 7 9] and B=[2 4 6 8], how can I create C=[1 2 3 4 5 6 7 8 9]?
Youssef Khmou 2015-1-15
编辑：Youssef Khmou 2015-1-15
This question is general due to the variation of array dimensions, however for a particular case you described, vectors A and B can be mixed by single loop, so the following scheme is valid only when dim(A)=dim(B)+1 as in the example :
A=[1 3 5 7 9];
B=[2 4 6 8];
C=[C A(t) B(t)];
For those who are interested, some references as to why array concatenation in a loop is poor coding practice in MATLAB:
This can be done simply using indexing, without any loops:
>> A = [1,3,5,7,9];
>> B = [2,4,6,8];
>> C(1:2:2*numel(A)) = A;
>> C(2:2:end) = B
1 2 3 4 5 6 7 8 9
This solution also assumes that numel(A)==numel(B)+1.
Most importantly, for larger arrays this code will be much faster than the accepted solution, so it is the most universal solution.
Find more on Multidimensional Arrays 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!