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

467 views (last 30 days)
srycandy on 28 Jul 2011
Answered: James Tursa on 2 Nov 2017
hello.. i hv a question. what is the command to call the non diagonal entries of a matrix? tq very much...

Rick Rosson on 28 Jul 2011
M = 8;
N = 5;
X = randn(M,N);
idx = eye(M,N);
Y = (1-idx).*X;
Z = X(~idx);
HTH.
Best, Rick
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
Rick Rosson on 28 Jul 2011

Nathan Greco on 28 Jul 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.
srycandy on 28 Jul 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..

dor eivensitz on 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
James Tursa on 2 Nov 2017
Please open up a new question for this, and provide a short example in that new question.

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