Expanding a Matrix with Repmat/Reshape?

9 ビュー (過去 30 日間)
Jonny
Jonny 2017 年 8 月 18 日
回答済み: Jan 2017 年 8 月 18 日
I have two vectors:
x = [3 6 7 10]
y = [2 2 2 4]
I am trying to create vector
z = [3 3 6 6 7 7 10 10 10 10]
So each element x(i) is repeated y(i) times. This is straight forward with a for loop, but I'm trying to avoid looping, if possible. The size and values of x and y may change as well (they are populated by variables).
Here's the loop version:
z= [];
for i = 1:numel(y)
z= [z, repmat(x(i), 1, y(i))];
end
Any help is appreciated.

採用された回答

James Tursa
James Tursa 2017 年 8 月 18 日
編集済み: James Tursa 2017 年 8 月 18 日
E.g.,
z = cell2mat(cellfun(@(x,y)repmat(x,1,y),num2cell(x),num2cell(y),'Uni',false));
But this just hides the loops in the background.

その他の回答 (3 件)

Steven Lord
Steven Lord 2017 年 8 月 18 日
If you're using release R2015a or later, use repelem.
x = [3 6 7 10];
y = [2 2 2 4];
z = repelem(x, y)

Matt J
Matt J 2017 年 8 月 18 日
編集済み: Matt J 2017 年 8 月 18 日
Here's a truly loop free method,
clear p
p(cumsum(y,'reverse'))=1;
z=x(cumsum(flip(p)))

Jan
Jan 2017 年 8 月 18 日
x = [3 6 7 10]
y = [2 2 2 4]
z = repelem(x, y);
Or if this is the bottleneck of your code, try FEX: RunLength:
Z = RunLength(x, y);

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by