How to vectorize row-wise diagonalization of a matrix

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

    Here's a simple vectorized solution, assuming X is the input matrix:

    Y = repmat(eye(size(X, 2)), size(X, 1), 1);
    Y(find(Y)) = X;
    

    Another alternative is to use sparse, and this can be written as a neat one-liner:

    Y = full(sparse(1:numel(X), repmat(1:size(X, 2), 1, size(X, 1)), X'));
    

提交回复
热议问题