I have an n-by-m matrix that I want to convert to a mn-by-m matrix, with each m-by-m block of the result containing the diagonal of each row.
For example, if the input is:
[1 2; 3 4; 5 6]
the output should be:
[1 0; 0 2; 3 0; 0 4; 5 0; 0 6]
Of course, I don't want to assemble the matrix step by step myself with a for
loop.
Is there a vectorized and simple way to achieve this?
The easiest way I see to do this is actually quite simple, using simple index referencing and the reshape function:
If you examine
J
, it looks like this:Matrix
K
is just what wanted:As Eitan T has noted in the comments, the above is specific to the example, and doesn't cover the general solution. So below is the general solution, with m and n as described in the question.
If you want to test it to see it working, just use
Note: if J already exists, this can cause problems. In this case, you need to also use
It may not be the most computationally efficient solution, but here's a 1-liner using
kron
:This can be generalized if A is n x m:
For a vectorized way to do this, create the linear indices of the diagonal elements into the resulting matrix, and assign directly.
Here's a simple vectorized solution, assuming
X
is the input matrix:Another alternative is to use
sparse
, and this can be written as a neat one-liner: