フィルターのクリア

Which MATLAB function can remove the diagonal elements of a NxN matrix

36 ビュー (過去 30 日間)
Jinlong Wei
Jinlong Wei 2011 年 2 月 1 日
編集済み: oren Tadmor 2014 年 6 月 12 日
Do you know which MATLAB function can do the following work: to remove the diagonal elements of a (N+1)x(N+1) matrix to generate a new NxN matrix.
For say, the old matrix is
[ 0 1 2 3
1 0 2 3
1 2 0 3
1 2 3 0 ]
the generated new matrix is
[ 1 2 3
1 2 3
1 2 3 ]
  1 件のコメント
Kenneth Eaton
Kenneth Eaton 2011 年 2 月 1 日
It's not clear what you are asking. In your example, removing the main diagonal still leaves you with (N+1)*N elements, too many to make an N-by-N matrix. You would have to remove the main diagonal plus either the first superdiagonal or the first subdiagonal to end up with N*N elements.

サインインしてコメントする。

採用された回答

Matt Fig
Matt Fig 2011 年 2 月 1 日
Your example doesn't add up, as Kenneth mentioned. However, in general you could do something like this:
A = [ 0 1 2 3
1 0 2 3
1 2 0 3
1 2 3 0 ];
A(logical(eye(size(A)))) = []; % Or A = A(~eye(size(A)))
A = reshape(A,4,3); % Or 3,4 or whatever.
  2 件のコメント
Paulo Silva
Paulo Silva 2011 年 2 月 1 日
A(A==0)=[]
A = reshape(A,4,3);
James Tursa
James Tursa 2013 年 1 月 30 日
編集済み: James Tursa 2013 年 1 月 30 日
Another variation using linear indexing:
m = size(A,1)+1;
A(1:m:end) = [];
A = reshape(A,4,3); % or whatever

サインインしてコメントする。

その他の回答 (3 件)

Paulo Silva
Paulo Silva 2011 年 2 月 1 日
b=triu(a)
b=b(:,2:end)
c=tril(a)
c=c(:,1:end-1)
b+c
  1 件のコメント
ahahahaaron
ahahahaaron 2013 年 1 月 30 日
this one produces an overlap and doesn't really produce what the other guy wants.

サインインしてコメントする。


oren Tadmor
oren Tadmor 2014 年 6 月 12 日
編集済み: oren Tadmor 2014 年 6 月 12 日
remove_diagonal = @(t)reshape(t(~diag(ones(1,size(t, 1)))), size(t)-[1 0]);
So :
>> m = magic(5)
m =
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
ans =
23 24 1 8 15
4 6 7 14 16
10 12 19 20 22
11 18 25 2 3

Youssef  Khmou
Youssef Khmou 2013 年 1 月 31 日
編集済み: Youssef Khmou 2013 年 1 月 31 日
hi, Jinlong Wei
According to your example : Here is a function :
function Z=diagrem(X)
N=size(X);
Z=X;
if N(1)~=N(2)
error('Matrix is not square');
end
for x=1:N(1)
Z(x,x)=0;
end
for y=1:N(1)-1
Z(y,y+1)=0;
end
Z(Z==0)=[];
Z=reshape(Z,N(1)-1,N(2)-1);
It produces exactly your example ,it removes R(i,i) and in the second loop it removes R(j,j+1) with 1<=i<=n , 1<=j<n .
  1 件のコメント
Youssef  Khmou
Youssef Khmou 2013 年 1 月 31 日
In case your matrix already contains zeros, then change the code by giving Z(x,x) and Z(y,y+1) a NaN value per example or something else then remove them.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by