What is a function that takes the diagonal of a matrix (N) and converts the diagonal to all zeros.

 採用された回答

try :
function Y=diagzero(X)
N=size(X);
if N(1)~=N(2)
error(' Matrix not square');
end
Y=X;
for x=1:N(1)
Y(x,x)=0;
end

その他の回答 (4 件)

James Tursa
James Tursa 2013 年 4 月 10 日
編集済み: James Tursa 2013 年 4 月 10 日
Another method if you know m is square:
r = size(m,1) + 1;
m(1:r:end) = 0;
If you don't know if m is square or not you could do this:
r = size(m,1);
n = min(numel(m),r*r);
m(1:r+1:n) = 0;
m(eye(size(m))>0) = 0;

1 件のコメント

Or to avoid testing all those 0's:
m(speye(size(m))>0) = 0;
or:
m(logical(speye(size(m)))) = 0;

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

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 4 月 9 日
編集済み: Azzi Abdelmalek 2013 年 4 月 9 日
ii=1:size(m,1);
m(sub2ind(size(m),ii,ii))=0
Jonathan Epperl
Jonathan Epperl 2013 年 4 月 10 日
編集済み: Jonathan Epperl 2013 年 4 月 10 日
Assuming m is square (because else you'd have to define the diagonal for me):
diagzero = @(m) m - diag(diag(m));

1 件のコメント

James Tursa
James Tursa 2013 年 4 月 10 日
Doesn't work on any diagonal elements that are inf or nan.

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

カテゴリ

ヘルプ センター および File Exchange で Operating on Diagonal Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by