How to convert matrix to a stack of diagonal matrices based on every row?

后端 未结 5 1651
既然无缘
既然无缘 2021-01-20 10:52

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          


        
5条回答
  •  盖世英雄少女心
    2021-01-20 11:19

    An alternative, which (for me) is faster than any of the methods benchmarked above (for large and small matrices) is

    [m,n] = size(A);
    Z(n,m*n) = 0;
    for idx = 1:n
         Z(idx,((idx-1)*m+1):(idx*m)) = A(:,idx);
    end
    Z = reshape(Z,m*n,n);
    

提交回复
热议问题