How to replace the diagonal entries of a square matrix with entries from a vectore of equal length?

406 views (last 30 days)
I have an nxn matrix M, and a vector v of length n. I want to swap the diagonal of M with the vector v, without a for loop. Is that possible? Thanks!

Accepted Answer

John D'Errico
John D'Errico on 6 Apr 2018
Edited: John D'Errico on 6 Apr 2018
M = M - diag(diag(M)) + diag(v)
or...
M = M + diag(v - diag(M))
In either case, I killed the diagonal, then added the diagonal I want back in.
Or, you can simply replace those elements. A lazy way to do that is:
M(find(eye(size(M))) = v;
There are lots of simple variations on the latter theme of course.
n = size(M,1);
M(1:(n+1):end) = v;
For example:
M = rand(5)
M =
0.45054 0.82582 0.10665 0.86869 0.43141
0.083821 0.53834 0.9619 0.084436 0.91065
0.22898 0.99613 0.0046342 0.39978 0.18185
0.91334 0.078176 0.77491 0.25987 0.2638
0.15238 0.44268 0.8173 0.80007 0.14554
v = 1:5;
n = size(M,1);
M(1:(n+1):end) = v
M =
1 0.82582 0.10665 0.86869 0.43141
0.083821 2 0.9619 0.084436 0.91065
0.22898 0.99613 3 0.39978 0.18185
0.91334 0.078176 0.77491 4 0.2638
0.15238 0.44268 0.8173 0.80007 5
  7 Comments
Julio César Sayago Cabrera
1000 Thanks, so simple and so good. I had a while thinking about it and couldn't come up with a solution. Many times the most simple way of do it is the best of them all

Sign in to comment.

More Answers (1)

Fangjun Jiang
Fangjun Jiang on 6 Apr 2018
a=rand(5);
a(boolean(eye(5)))=1:5

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!