Filter löschen
Filter löschen

Replace loop to create a matrix

2 Ansichten (letzte 30 Tage)
Adrián Martínez Rodríguez
Bearbeitet: Matt J am 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?

Akzeptierte Antwort

Matt J
Matt J am 19 Nov. 2021
Bearbeitet: Matt J am 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

Weitere Antworten (0)

Kategorien

Mehr zu Multidimensional Arrays finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by