フィルターのクリア

How to duplicate rows of a matrix if the number of copies for each row are different?

14 ビュー (過去 30 日間)
Hi all,
I want to duplicate each rows of a matrix according to the numbers given in a vector.
For example, I have matrix A and vector , I want to duplicate the first row of A 2 times, second row by 4 times and third row by 5 times.
Is there any way to do this?
Thank you for your help.

採用された回答

Stephen23
Stephen23 2021 年 11 月 9 日
編集済み: Stephen23 2021 年 11 月 9 日
out = repelem(A,b,1)
  3 件のコメント
Stephen23
Stephen23 2021 年 11 月 9 日
編集済み: Stephen23 2021 年 11 月 9 日
Use REPELEM, not REPMAT. Assuming that your matrix A has as many rows as b has elements:
A = randi(9,3,4)
A = 3×4
1 5 2 6 5 9 8 6 2 2 7 4
b = [2,4,5];
out = repelem(A,b,1)
out = 11×4
1 5 2 6 1 5 2 6 5 9 8 6 5 9 8 6 5 9 8 6 5 9 8 6 2 2 7 4 2 2 7 4 2 2 7 4 2 2 7 4
This is much simpler and more efficient than using a WHILE or FOR loop.
Hung Dao
Hung Dao 2021 年 11 月 9 日
Thank you very much. This is exactly what I need.

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

その他の回答 (2 件)

KSSV
KSSV 2021 年 11 月 9 日
Read about repmat.
b = [2 4 5] ;
A = repmat(b,2,1)
A = 2×3
2 4 5 2 4 5
B = repmat(b,3,1)
B = 3×3
2 4 5 2 4 5 2 4 5
  1 件のコメント
Hung Dao
Hung Dao 2021 年 11 月 9 日
Thanks for your answer but that is not really what I am asking for.

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


Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021 年 11 月 9 日
It can be done in a few different ways, e.g.:
A = magic(3)
A = 3×3
8 1 6 3 5 7 4 9 2
b = [2, 4, 5];
AA = [repmat(A(1,:), b(1),1);repmat(A(2,:), b(2),1); repmat(A(3,:), b(3),1)]
AA = 11×3
8 1 6 8 1 6 3 5 7 3 5 7 3 5 7 3 5 7 4 9 2 4 9 2 4 9 2 4 9 2
% Alternative way:
A = magic(3);
b = [2, 4, 5];
AA =[];
for ii = 1:numel(b)
AA = [AA; repmat(A(ii,:), b(ii),1)];
end
AA
AA = 11×3
8 1 6 8 1 6 3 5 7 3 5 7 3 5 7 3 5 7 4 9 2 4 9 2 4 9 2 4 9 2
  2 件のコメント
Hung Dao
Hung Dao 2021 年 11 月 9 日
Thank you very much.
I am wondering if there is a more efficient way than using a forloop?
Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021 年 11 月 9 日
I don't believe there is an alternative more efficient way than using [for .. end] or [while .. end] loop.

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by