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

后端 未结 5 1656
既然无缘
既然无缘 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条回答
  •  旧时难觅i
    2021-01-20 11:20

    This code converts A to a cell array of row vectors, applies the diag function to each, and then stacks them:

    D = cellfun(@diag,mat2cell(A, ones(size(A,1), 1), size(A,2)), 'UniformOutput', false);
    B = vertcat(D{:});
    

    Results:

    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
    

提交回复
热议问题