0

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?

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
mHelpMe
  • 6,336
  • 24
  • 75
  • 150

1 Answers1

4
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.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147