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

后端 未结 7 1565
名媛妹妹
名媛妹妹 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:23
    A = zeros(7,6);
    V = [1 3 5];
    
    [n m] = size(A);
    diagIdx = 1:n+1:n*m;
    A( diagIdx(V) ) = 1
    
    A =
         1     0     0     0     0     0
         0     0     0     0     0     0
         0     0     1     0     0     0
         0     0     0     0     0     0
         0     0     0     0     1     0
         0     0     0     0     0     0
         0     0     0     0     0     0
    
    0 讨论(0)
提交回复
热议问题