Let's say I have a matrix in MATLAB like
A = [1 2 3;
4 5 6;
7 8 9]
and I would like to obtain a matrix of the form
B = [1 0 0;
0 4 0;
0 0 7;
2 0 0;
0 5 0;
0 0 8;
3 0 0;
0 6 0;
0 0 9]
i.e. a matrix that is a concatenation of three diagonal matrices, with each having the columns of matrix A
at their diagonals. I know how to do this using a for
loop over the columns of A
and then concatenating all the results but I am looking for a shorter way to do this. Please share your ideas.
B(repmat(eye(3),3,1)==1) = A;
reshape(B, [], 3)