Alternative to blkdiag and mat2cell functions
Show older comments
Hi all,
I currently have a code which takes some matrix A and stacks each row of the aforementioned matrix in to a block diagonal matrx C such that:
The code for that is:
Nc = 10 ; % Number of rows of A
Nb = 4 ; % Number of columns of A
A = randn(Nc, Nb) ;
B = mat2cell(A, ones(Nc, 1), Nb) ;
C = blkdiag(B{:}) ;
Generating matrix C however is extremely slow as I run a similar piece of code as shown above a couple of thousands of times. From timing the entire thing, MATLAB has pointed out that the mat2cell and blkdiag functions are by far the slowest ones, so I thought I should replace them in the following way:
Nb = 4 ;
Nc = 10 ;
A = randn(Nc, Nb) ;
C = zeros(Nc, Nb*Nc) ; % preallocate C
ridx = repmat(1:Nc, 1, Nb)' ; % row indices of where each element of A should be in C
cidx = reshape(reshape(1:Nb*Nc, Nb, Nc)', [], 1) ; % column indices of where each element of A should be in C
C(ridx, cidx) = A ;
In short, the above code simply spots the indices of where all the elements of matrix A should be allocated on matrix C, thus cidx is the row indices and ridx is the column indices.
Even though these indices are correct, this code returns an error as the matrix C(ridx, cidx) is a [Nb*Nc x Nb*Nc] matrix (or 40x40 in this case), and A is a [Nc x Nb] matrix. I did not expect that since ridx and cidx are column vectors representing indices, so I would simply expect that all the elements of A would transfer to C at the specified indices.
So how can I make the above code run correctly?
Thanks for your help in advance.
2 Comments
Bruno Luong
on 13 Dec 2020
You clearly didn't run the code
Nc = 10 ; % Number of rows of A
Nb = 4 ; % Number of columns of A
A = randn(Nb, Nc) ;
B = mat2cell(A, onces(Nc, 1), Nb) ;
C = blkdiag(B{:}) ;
KostasK
on 13 Dec 2020
Accepted Answer
More Answers (2)
Bruno Luong
on 13 Dec 2020
What about about a simple for-loop
[Nb,Nc] = size(A);
C = zeros(Nb,Nb*Nc);
for r=1:Nb
C(r,(r-1)*Nc+(1:Nc)) = A(r,:);
end
Bruno Luong
on 13 Dec 2020
Edited: Bruno Luong
on 13 Dec 2020
[I,J] = ndgrid(1:Nb,1:Nc);
C = accumarray([I(:),J(:)+(I(:)-1)*Nc],A(:));
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!