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
Youssef Khmou 2015 年 1 月 15 日
編集済み: Youssef Khmou 2015 年 1 月 15 日

0 投票

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];
n=min(length(A),length(B));
C=[];
for t=1:n
C=[C A(t) B(t)];
end
C=[C A(end)];

3 件のコメント

Alex Strongholm
Alex Strongholm 2015 年 1 月 15 日
That's it, thank you very much
Stephen23
Stephen23 2015 年 1 月 15 日
編集済み: Stephen23 2015 年 1 月 18 日
This answer is very poor use of MATLAB.
The use of a for loop and concatenating scalar values onto the end of with every iteration is poor coding practice in MATLAB. If the arrays are large, then this will be slow as MATLAB keeps expanding the array and copying it to new memory. One solution is to preallocate the array.
For a much neater and simpler solution see my answer below.
Stephen23
Stephen23 2015 年 1 月 15 日
編集済み: Stephen23 2015 年 1 月 15 日

サインインしてコメントする。

その他の回答 (1 件)

Stephen23
Stephen23 2015 年 1 月 15 日
編集済み: Stephen23 2015 年 1 月 16 日

1 投票

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
C =
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.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2015 年 1 月 15 日

編集済み:

2015 年 1 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by