I have a square matrix n x n & I also have a vector which is n x 1. I want to replace the diagonal elements with the values in my vector.
Is there a way of doing this in Matlab without looping?
I have a square matrix n x n & I also have a vector which is n x 1. I want to replace the diagonal elements with the values in my vector.
Is there a way of doing this in Matlab without looping?
matrix(1:n+1:end) = vector;
Explanation: if you use a single index into a matrix (that's called linear indexing), Matlab counts the elements down the first column, then second column etc. A step of n+1
thus defines the diagonal.