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

后端 未结 7 1750
名媛妹妹
名媛妹妹 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

    I'd use sub2ind and pass the diagonal indices as both x and y parameters:

    A = zeros(4)
    V=[2 4]
    
    idx = sub2ind(size(A), V,V)
    % idx = [6, 16]
    
    A(idx) = 1
    
    % A =
    % 0     0     0     0
    % 0     1     0     0
    % 0     0     0     0
    % 0     0     0     1
    

提交回复
热议问题