How to create a vector from two vectors?

7 次查看(过去 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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by