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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With