Replace loop to create a matrix

2 visualizzazioni (ultimi 30 giorni)
Adrián Martínez Rodríguez
Modificato: Matt J il 19 Nov 2021
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?

Risposta accettata

Matt J
Matt J il 19 Nov 2021
Modificato: Matt J il 19 Nov 2021
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

Più risposte (0)

Categorie

Scopri di più su Multidimensional Arrays in Help Center e File Exchange

Tag

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by