Replace loop to create a matrix

2 ビュー (過去 30 日間)
Adrián Martínez Rodríguez
Adrián Martínez Rodríguez 2021 年 11 月 19 日
編集済み: Matt J 2021 年 11 月 19 日
Hello,
I want to create a matrix using the following code:
groupid = [1; 1; 1; 2; 2; 3; 3;];
data.id = groupid;
denominador(data)
ans =
(1,1) 1 (2,1) 1 (3,1) 1 (2,2) 1 (3,2) 1 (3,3) 1 (4,4) 1 (5,4) 1 (5,5) 1 (6,6) 1 (7,6) 1 (7,7) 1
function f = denominador(X)
[GC, GR] = groupcounts(X.id);
args = cell(size(GR, 1));
for i = 1:size(GR, 1)
args{i} = sparse(tril(ones(GC(i))));
end
f = blkdiag(args{:});
end
The matrix created is C:
As you can see above, I am creating a sparse matrix where the diag is composed of lower triangular arrays of ones with dimensions equal to the number of times each "id" appears, and the elements outside the diag are zero.
Is there any function that can replicate in a more efficient way (without a loop) the function "denominador"? Is there any function similar to "sparse" than can be used to create matrix C?

採用された回答

Matt J
Matt J 2021 年 11 月 19 日
編集済み: Matt J 2021 年 11 月 19 日
This might be a more efficient way to build arg, but I suspect that your bottleneck will be in blkdiag().
function f = denominador(X)
GC = groupcounts(X.id);
args=arrayfun(@(i) sparse(tril(ones(i))) ,1:max(GC),'uni',0 );
args=args(GC);
f = blkdiag(args{:});
end
  1 件のコメント
Adrián Martínez Rodríguez
Adrián Martínez Rodríguez 2021 年 11 月 19 日
Thanks! It works.

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by