How to create a vector from two vectors?

7 ビュー (過去 30 日間)
DS Chen
DS Chen 2016 年 8 月 30 日
コメント済み: DS Chen 2016 年 8 月 30 日
I have two vectors with the same length:
A = [2 4 5 4 9 8 1 6];
B = [3 6 2 5 4 4 3 5];
Each element in vector B defines how many times the corresponding element in vector A duplicates itself. For example, here I want the final vector C to have 3 twos, 6 fours, 2 fives, 5 fours, 4 nines, 4 eights, 3 ones, and 5 sixes:
C = [2 2 2, 4 4 4 4 4 4, 5 5, 4 4 4 4 4, 9 9 9 9, 8 8 8 8, 1 1 1, 6 6 6 6 6];
I can do it with a for-loop. However in practice, vectors A and B are long. So is there a way to do this without a loop.
Thanks!

採用された回答

Stephen23
Stephen23 2016 年 8 月 30 日
編集済み: Stephen23 2016 年 8 月 30 日
If you have MATLAB 2015a or more recent then use repelem:
repelem(A,B)
otherwise:
cell2mat(arrayfun(@(a,b)repmat(a,1,b),A,B,'Uni',0))
although a loop may well be faster.
  3 件のコメント
Stephen23
Stephen23 2016 年 8 月 30 日
編集済み: Stephen23 2016 年 8 月 30 日
Important: do NOT expand the array in the loop! Use a preallocated cell array:
>> C = cell(size(A));
>> for k = 1:numel(C), C{k} = repmat(A(k),1,B(k)); end
>> cell2mat(C)
Or a preallocated numeric array (this is faster):
>> X = cumsum([0,B]);
>> D = NaN(1,X(end));
>> for k = 1:numel(A), D(1+X(k):X(k+1)) = A(k); end
DS Chen
DS Chen 2016 年 8 月 30 日
Good Point!
Using preallocated cell array is 40 times faster than expanding array in the loop.
I also test the repelem(A, B) on the other machine. repelem(A,B) is indeed the fastest! It's at least 10 times faster than for-loop. I hope I can use it later:)

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by