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

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

    >> tt = zeros(5,5)
    tt =
         0     0     0     0     0
         0     0     0     0     0
         0     0     0     0     0
         0     0     0     0     0
         0     0     0     0     0
    >> tt(1:6:end) = 3
    tt =
         3     0     0     0     0
         0     3     0     0     0
         0     0     3     0     0
         0     0     0     3     0
         0     0     0     0     3
    

    and more general:

    >> V=[1 2 5]; N=5;
    >> tt = zeros(N,N);
    >> tt((N+1)*(V-1)+1) = 3
    tt =
         3     0     0     0     0
         0     3     0     0     0
         0     0     0     0     0
         0     0     0     0     0
         0     0     0     0     3
    

    This is based on the fact that matrices can be accessed as one-dimensional arrays (vectors), where the 2 indices (m,n) are replaced by a linear mapping m*N+n.

提交回复
热议问题