Reputation: 107
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)
Upvotes: 5
Views: 3252
Reputation: 420991
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
Upvotes: 5
Reputation: 4115
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);
Upvotes: 3
Reputation: 78316
Here's another way
reshape(A(setdiff(1:9,1:4:9)),[3,2])
Upvotes: 0