Repeating the rows of an array by a number given by another array

1 回表示 (過去 30 日間)
Saeid
Saeid 2022 年 2 月 17 日
コメント済み: Saeid 2022 年 2 月 19 日
Consider the array:
x=[linspace(1,4,4)' linspace(5,20,4)']
x = 4×2
1 5 2 10 3 15 4 20
I would like to repeat each row by a number given by another array such as
I=[2 3 2 1]'
I = 4×1
2 3 2 1
so that at the end the first row of x is repeat twice, the second row is repeated 3 times and so on.
Is this possible without using a loop?

採用された回答

Jan
Jan 2022 年 2 月 19 日
編集済み: Jan 2022 年 2 月 19 日
Use repelem, which is the built-in efficient solution for repeating elements:
x = [linspace(1,4,4)' linspace(5,20,4)']
x = 4×2
1 5 2 10 3 15 4 20
I = [2 3 2 1];
y = repelem(x, I, 1)
y = 8×2
1 5 1 5 2 10 2 10 2 10 3 15 3 15 4 20
A speed comparison:
x = rand(1e4, 2);
I = repmat(1:10, 1, 1000);
tic
for k = 1:100
C = cell(length(I),1) ;
for i = 1:length(C)
C{i} = repmat(x(i,:),I(i),1) ;
end
C = cell2mat(C);
end
toc
tic
for k = 1:100 % Slightly modified for I is a row vector:
idx = arrayfun(@(x,y)x*ones(1,y),1:numel(I),I,'UniformOutput',false);
C = x([idx{:}],:);
end
toc
tic
for k = 1:100
C = repelem(x, I, 1);
end
toc
% R2018b:
% Elapsed time is 3.676185 seconds. loop
% Elapsed time is 6.848004 seconds. arrayfun
% Elapsed time is 0.038391 seconds. repelem
  2 件のコメント
Mike Croucher
Mike Croucher 2022 年 2 月 19 日
Nice!
Saeid
Saeid 2022 年 2 月 19 日
Wow, so there IS a difference! Thanks Jan!

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

その他の回答 (1 件)

KSSV
KSSV 2022 年 2 月 17 日
x=[linspace(1,4,4)' linspace(5,20,4)'] ;
I=[2 3 2 1]' ;
C = cell(length(I),1) ;
for i = 1:length(C)
C{i} = repmat(x(i,:),I(i),1) ;
end
C = cell2mat(C)
C = 8×2
1 5 1 5 2 10 2 10 2 10 3 15 3 15 4 20
  4 件のコメント
Mike Croucher
Mike Croucher 2022 年 2 月 17 日
OK good! There has been a lot of work done by MathWorks in recent years on improving the efficiency of loops. You do not need to be afraid of them any more. In many cases, they are on par with vectorised methods.
If the algorithm can be expressed naturally as a loop, do so. Only worry about other methods if the performance is problematic.
Saeid
Saeid 2022 年 2 月 17 日
Thanks, Mike!

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by