Add a diagonal of zeros to a matrix in MATLAB

后端 未结 3 1337
温柔的废话
温柔的废话 2021-01-12 03:27

Suppose I have a matrix A of dimension Nx(N-1) in MATLAB, e.g.

N=5;
A=[1  2  3  4;
   5  6  7  8;
   9  10 11 12;
   13 14 15 16;
          


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-12 04:18

    If you want to insert any vector on a diagonal of a matrix, one can use plain indexing. The following snippet gives you the indices of the desired diagonal, given the size of the square matrix n (matrix is n by n), and the number of the diagonal k, where k=0 corresponds to the main diagonal, positive numbers of k to upper diagonals and negative numbers of k to lower diagonals. ixd finally gives you the 2D indices.

    function [idx] = diagidx(n,k)
    % n size of square matrix
    % k number of diagonal
    if k==0 % identity
        idx = [(1:n).' (1:n).']; % [row col]
    elseif k>0 % Upper diagonal
        idx = [(1:n-k).' (1+k:n).'];
    elseif k<0 % lower diagonal
        idx = [(1+abs(k):n).' (1:n-abs(k)).'];
    end
    end
    

    Usage:

    n=10;
    k=3;
    A = rand(n);
    idx = diagidx(n,k);
    
    A(idx) = 1:(n-k);
    

提交回复
热议问题