How to assign values to a MATLAB matrix on the diagonal?

后端 未结 7 1681
名媛妹妹
名媛妹妹 2020-11-27 03:45

Suppose I have an NxN matrix A, an index vector V consisting of a subset of the numbers 1:N, and a value K, and I want to do this:

 for i = V
     A(i,i) = K         


        
7条回答
  •  失恋的感觉
    2020-11-27 04:15

    I use this small inline function in finite difference code.

    A=zeros(6,3);
    range=@(A,i)[1-min(i,0):size(A,1)-max(i+size(A,1)-size(A,2),0 ) ];
    Diag=@(A,i) sub2ind(size(A), range(A,i),range(A,i)+i );
    A(Diag(A, 0))= 10; %set diagonal 
    A(Diag(A, 1))= 20; %equivelent to diag(A,1)=20;
    A(Diag(A,-1))=-20; %equivelent to diag(A,-1)=-20;
    

    It can be easily modified to work on a sub-range of the diagonal by changing the function range.

提交回复
热议问题