How to create a vector from two vectors?

조회 수: 1 (최근 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 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