I need a code to omit the diagonal elements of a matrix for example if
A =
[1 2 3;
1 2 3;
1 2 3];
the the output come:
[2 3;
1 3;
1 2];
how can i do it simply ( i know a long one but i need it simple)
Here's one solution:
Alower = tril(A, -1);
Aupper = triu(A, 1);
result = Alower(:, 1:end-1) + Aupper(:, 2:end)
Demo:
> A = [1 2 3; 1 2 3; 1 2 3]
A =
1 2 3
1 2 3
1 2 3
> tril(A, -1)(1:end, 1:end-1) + triu(A, 1)(1:end, 2:end)
ans =
2 3
1 3
1 2
Notice that there are two possibilities after you eliminate the diagonal of a n
by n
matirx:
If the aftermath matrix is n
by n-1
(like in your question), you can do it by:
A=A'; A(1:n+1:n*n)=[]; A=reshape(A,n-1,n)';
If the aftermath matrix is n-1
by n
, you can do it like this:
A(1:n+1:n*n)=[]; A=reshape(A,n-1,n);
这是另一种方式
reshape(A(setdiff(1:9,1:4:9)),[3,2])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.