Matlab矩阵赋值问题

来源:百度知道 编辑:UC知道 时间:2024/05/14 11:35:38
怎么生成一个次对角阵
就是只有一个次对角线非0,其余元素均为0
次对角线上使只有第一个元素为1,其他的元素为2
有没有不用循环的高阶一点的办法

X = diag(v,k)
以向量v的元素作为矩阵X的第k条对角线元素,当k=0时,v为X的主对角线;当k>0时,v为上方第k条对角线;当k<0时,v为下方第k条对角线。
例:
>> v=[1 2 3];
>> x=diag(v,-1)
x =
0 0 0 0
1 0 0 0
0 2 0 0
0 0 3 0
下面不知是否是你想要的:
>> clear
>> v(1)=1;
>> n=5;%可以安自己需求
>> v(2:n)=2;
>> x=diag(v,-1)

x =

0 0 0 0 0 0
1 0 0 0 0 0
0 2 0 0 0 0
0 0 2 0 0 0
0 0 0 2 0 0
0 0 0 0 2 0

help diag
DIAG Diagonal matrices and diagonals of a matrix.
DIAG(V,K) when V is a vector with N components is a square matrix
of order N+ABS(K) with the elements of V on the K-th diagonal. K = 0
is the main diagonal, K > 0 is above the main diagonal and K &l