How to vectorize row-wise diagonalization of a matrix

后端 未结 4 1643
無奈伤痛
無奈伤痛 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:18

    The easiest way I see to do this is actually quite simple, using simple index referencing and the reshape function:

    I = [1 2; 3 4; 5 6];
    J(:,[1,4]) = I;
    K = reshape(J',2,6)';
    

    If you examine J, it looks like this:

    J =
         1     0     0     2
         3     0     0     4
         5     0     0     6
    

    Matrix K is just what wanted:

    K =
         1     0
         0     2
         3     0
         0     4
         5     0
         0     6
    

    As Eitan T has noted in the comments, the above is specific to the example, and doesn't cover the general solution. So below is the general solution, with m and n as described in the question.

    J(:,1:(m+1):m^2) = I;
    K=reshape(J',m,m*n)';
    

    If you want to test it to see it working, just use

    I=reshape(1:(m*n),m,n)';
    

    Note: if J already exists, this can cause problems. In this case, you need to also use

    J=zeros(n,m^2);
    

提交回复
热议问题