且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

创建一个矩阵,该矩阵在任意偏移对角线上

更新时间:2023-11-03 23:52:16

diag 内置了以下功能:

diag has this functionality built in:

diag(ones(4,1),1)
ans =

     0     1     0     0     0
     0     0     1     0     0
     0     0     0     1     0
     0     0     0     0     1
     0     0     0     0     0

diag(ones(4,1),-1)

ans =

     0     0     0     0     0
     1     0     0     0     0
     0     1     0     0     0
     0     0     1     0     0
     0     0     0     1     0

diag(V,k)的语法是:V是要放在对角线上的向量(可以是1或任何奇数向量),而k是对角线的标签. 0是主对角线,正整数逐渐远离上对角线,负整数与下对角线相同;即k=1给出了第一个上对角线,k=-4给出了左下角.

Where the syntax of diag(V,k) is: V is the vector to be put on the diagonal (be it ones, or any odd vector), and k is the label of the diagonal. 0 is the main diagonal, positive integers are increasingly further away upper diagonals and negative integers the same for the lower diagonals; i.e. k=1 gives the first upper diagonal, k=-4 gives the lower left corner in this example.

出于完整性考虑,如果您只希望索引而不是完整矩阵(因为您建议将向量插入当前矩阵),则可以使用以下函数:

For completeness, if you just want the indices instead of a full matrix (since you suggested you wanted to insert a vector into a present matrix) you can use the following function:

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

其中idx的每一行都包含矩阵的索引.

where each row of idx contains the indices for the matrix.