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

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

    Suppose K is the value. The command

    A=A-diag(K-diag(A))
    

    may be a bit faster

    >> A=randn(10000,10000);
    
    >> tic;A(logical(eye(size(A))))=12;toc
    

    Elapsed time is 0.517575 seconds.

    >> tic;A=A+diag((99-diag(A)));toc
    

    Elapsed time is 0.353408 seconds.

    But it consumes more memory.

提交回复
热议问题