How to convert matrix to a stack of diagonal matrices based on every row?
问题 I have a matrix: A = [1 1 1 2 2 2 3 3 3] Is there a vectorized way of obtaining: B = [1 0 0 0 1 0 0 0 1 2 0 0 0 2 0 0 0 2 3 0 0 0 3 0 0 0 3] 回答1: Here's another way using sparse and repmat: A = [1 2 3; 4 5 6; 7 8 9]; A = A.'; B = full(sparse(1:numel(A), repmat(1:size(A,1),1,size(A,2)), A(:))); The original matrix is in A , and I transpose it so I can unroll the rows of each matrix properly for the next step. I use sparse to declare what is non-zero in a matrix. Specifically, we see that there