Borrar filtros
Borrar filtros

Replace loop to create a matrix

2 visualizaciones (últimos 30 días)
Adrián Martínez Rodríguez
Adrián Martínez Rodríguez el 19 de Nov. de 2021
Editada: Matt J el 19 de Nov. de 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?

Respuesta aceptada

Matt J
Matt J el 19 de Nov. de 2021
Editada: Matt J el 19 de Nov. de 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

Más respuestas (0)

Categorías

Más información sobre Multidimensional Arrays en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by