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

118 次查看(过去 30 天)
hello.. i hv a question. what is the command to call the non diagonal entries of a matrix? tq very much...

采纳的回答

Rick Rosson
Rick Rosson 2011-7-28
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 个评论
srycandy
srycandy 2011-7-28
i wanna keep the diagonal entries as well..and i also want the result also in 3x3 matrix..tq

请先登录,再进行评论。

更多回答(3 个)

Nathan Greco
Nathan Greco 2011-7-28
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 个评论
srycandy
srycandy 2011-7-28
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
dor eivensitz 2017-11-2
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
James Tursa 2017-11-2
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)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by