How do I access and modify only the non diagonal entries in a matrix?

35 vues (au cours des 30 derniers jours)
srycandy
srycandy le 28 Juil 2011
Commenté : Voss le 18 Juil 2024
hello.. i hv a question. what is the command to call the non diagonal entries of a matrix? tq very much...

Réponse acceptée

Rick Rosson
Rick Rosson le 28 Juil 2011
Please try the following:
M = 8;
N = 5;
X = randn(M,N);
idx = eye(M,N);
Y = (1-idx).*X;
Z = X(~idx);
HTH.
Best, Rick
Responding to your comment:
To multiply the non-diagonal elements by 2, please try:
A = [2 3 5;3 6 8;5 8 4];
idx = eye(size(A));
idx = idx + 2*(1-idx);
Y = idx.*A;
HTH.
Best, Rick
  4 commentaires
srycandy
srycandy le 28 Juil 2011
i wanna keep the diagonal entries as well..and i also want the result also in 3x3 matrix..tq
Rick Rosson
Rick Rosson le 28 Juil 2011
I modified my answer above.

Connectez-vous pour commenter.

Plus de réponses (4)

Nathan Greco
Nathan Greco le 28 Juil 2011
If tmp is your matrix, try:
tmp-diag(diag(tmp)) %works only with square matrices
OR
triu(tmp,1)+tril(tmp,-1)
Both of these set the diagonal entries to zero, essentially ignoring them. If this isn't what you want, please clarify.
  5 commentaires
Nathan Greco
Nathan Greco le 28 Juil 2011
OR: A.*2-diag(diag(A)) would work.
srycandy
srycandy le 28 Juil 2011
yup.. A.*2-diag(diag(A)) is the one i'm searching for.. i forgot to mentioned that i wanna keep the diagonal entries as well.. anyway, tq..

Connectez-vous pour commenter.


dor eivensitz
dor eivensitz le 2 Nov 2017
i want to keep both diagonal in matrix size i don't know, defined by n, and all other elements to multiply by them self plus 1. tnx
  1 commentaire
James Tursa
James Tursa le 2 Nov 2017
Please open up a new question for this, and provide a short example in that new question.

Connectez-vous pour commenter.


James Tursa
James Tursa le 2 Nov 2017
Another way for a square matrix:
M = your matrix
x = ~logical(eye(size(M)));
M(x) = 2*M(x); % <-- or whatever function you want on the rhs using M(x)

Niba Kainat
Niba Kainat le 18 Juil 2024
hi can someone tell me how to compute sum of no diagonal entries.
  1 commentaire
Voss
Voss le 18 Juil 2024
M = magic(4) % some square matrix
M = 4x4
16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
idx = ~eye(size(M)) % logical index indicating non-diagonal entries
idx = 4x4 logical array
0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0
result = sum(M(idx),'all') % sum the non-diagonal entries
result = 102

Connectez-vous pour commenter.

Catégories

En savoir plus sur Operating on Diagonal Matrices dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by