Replace loop to create a matrix

1 view (last 30 days)
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?

Accepted Answer

Matt J
Matt J on 19 Nov 2021
Edited: Matt J on 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

More Answers (0)

Categories

Find more on Multidimensional Arrays in Help Center and File Exchange

Tags

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!