How to vectorize row-wise diagonalization of a matrix

后端 未结 4 1788
無奈伤痛
無奈伤痛 2021-01-21 16:33

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 i

4条回答
  •  误落风尘
    2021-01-21 17:26

    It may not be the most computationally efficient solution, but here's a 1-liner using kron:

    A = [1 2; 3 4; 5 6];
    B = diag(reshape(A', 6, 1) * kron(ones(3, 1), eye(2))
    % B = 
    %     1     0
    %     0     2
    %     3     0
    %     0     4
    %     5     0
    %     0     6
    

    This can be generalized if A is n x m:

    diag(reshape(A.', n*m, 1)) * kron(ones(n,1), eye(m))
    

提交回复
热议问题