Alternation without for loop

2 ビュー (過去 30 日間)
JamJan
JamJan 2019 年 10 月 15 日
コメント済み: J. Alex Lee 2019 年 10 月 15 日
I have 2 vectors that I want to alternate
A = [1 2 3 4 5 6 7 8 9 10]
B = [0.5 0.2 0.4 0.8 0.9]
I would like to have the following output (preferably without for loop)
Output = [1 0.5 2 0.2 3 0.4 4 0.8 5 0.9 6 7 8 9 10]
How to do this?
Thanks!

回答 (3 件)

Stephen23
Stephen23 2019 年 10 月 15 日
編集済み: Stephen23 2019 年 10 月 15 日
>> N = min(numel(A),numel(B));
>> V = [reshape([A(1:N);B(1:N)],1,[]),A(N+1:end),B(N+1:end)]
V =
1 0.5 2 0.2 3 0.4 4 0.8 5 0.9 6 7 8 9 10
  1 件のコメント
J. Alex Lee
J. Alex Lee 2019 年 10 月 15 日
nice...i like when i didn't see the obvious complete opposite path...and i learned a new thing with the empty argument for reshape

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


Jos (10584)
Jos (10584) 2019 年 10 月 15 日
% a sorting trick
A = [1 2 3 4 5 6 7 8 9 10]
B = [0.5 0.2 0.4 0.8 0.9]
C = [A B] ;
[~,ix] = sort([1:numel(A) 1:numel(B)])
C = C(ix)

J. Alex Lee
J. Alex Lee 2019 年 10 月 15 日
Here's a possibility: if A and B were guaranteed to be the same length (your example is not) and row vectors, you could do
N = length(A)
Output = reshape([A(:),B(:)]',2*N,1)
If not same length, you can nan-pad the shorter vector and remove later.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by