How to vectorize row-wise diagonalization of a matrix

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

    For a vectorized way to do this, create the linear indices of the diagonal elements into the resulting matrix, and assign directly.

    %# create some input data
    inArray = [10 11;12 13;14 15];
    
    %# make the index array
    [nr,nc]=size(inArray);
    
    idxArray = reshape(1:nr*nc,nc,nr)';
    idxArray = bsxfun(@plus,idxArray,0:nr*nc:nr*nc^2-1);
    
    %# create output
    out = zeros(nr*nc,nc);
    out(idxArray) = inArray(:);
    
    out =
    
        10     0
         0    11
        12     0
         0    13
        14     0
         0    15
    

提交回复
热议问题