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

조회 수: 96 (최근 30일)
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!

채택된 답변

John D'Errico
John D'Errico 2018년 4월 6일
편집: John D'Errico 2018년 4월 6일
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
  댓글 수: 10
Uday
Uday 2024년 6월 10일
Please read John D'Errico's detailed explanation above on why
M(1:(n+1):end) = v;
works again.
John D'Errico
John D'Errico 2024년 6월 13일
M = rand(5)
M = 5x5
0.5108 0.7342 0.5212 0.0691 0.2529 0.4613 0.0433 0.2281 0.6686 0.3280 0.6924 0.1114 0.6931 0.0803 0.8222 0.9802 0.3333 0.5494 0.9603 0.1489 0.4885 0.3833 0.0137 0.5150 0.5014
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
% replace the super-diagonal with the numbers 1:4, using diag
M = M + diag((1:4)' - diag(M,1),1)
M = 5x5
0.5108 1.0000 0.5212 0.0691 0.2529 0.4613 0.0433 2.0000 0.6686 0.3280 0.6924 0.1114 0.6931 3.0000 0.8222 0.9802 0.3333 0.5494 0.9603 4.0000 0.4885 0.3833 0.0137 0.5150 0.5014
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
% replace the sub-diagonal, with the vector [2 3 5 7], using indexing
n = size(M,1);
M(2:n+1:end) = [2 3 5 7]
M = 5x5
0.5108 1.0000 0.5212 0.0691 0.2529 2.0000 0.0433 2.0000 0.6686 0.3280 0.6924 3.0000 0.6931 3.0000 0.8222 0.9802 0.3333 5.0000 0.9603 4.0000 0.4885 0.3833 0.0137 7.0000 0.5014
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Fangjun Jiang
Fangjun Jiang 2018년 4월 6일
a=rand(5);
a(boolean(eye(5)))=1:5

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by