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 40×40 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.
Best Answer