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

后端 未结 7 1739
名媛妹妹
名媛妹妹 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:10

    >> B=[0,4,4;4,0,4;4,4,0]
    
    B =
    
         0     4     4
         4     0     4
         4     4     0
    
    >> v=[1,2,3]
    
    v =
    
         1     2     3
    
    >> B(eye(size(B))==1)=v
    %insert values from v to eye positions in B
    
    B =
    
         1     4     4
         4     2     4
         4     4     3
    

提交回复
热议问题