フィルターのクリア

How to replace the diagonal elements of a matrix with 0 fro avoiding self loops?

232 ビュー (過去 30 日間)
SUNANNA S S
SUNANNA S S 2017 年 4 月 19 日
コメント済み: tommsch 2024 年 6 月 28 日 8:33
I have a matrix
M= 1 0 0 0 1 0
0 1 0 1 0 0
0 0 1 0 1 1
1 0 0 1 0 0
1 1 1 0 0 0
0 0 0 1 0 1
I want to replace all the diagonal elements in this matrix to 0 if it is 1.
  1 件のコメント
Ramtin Nazerian
Ramtin Nazerian 2022 年 12 月 21 日
Out = M.*-(eye(height(M))-1);
This will make all the diagonal values of your matrix zero as long as the matrix is square. hope that helps :).

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

採用された回答

Andrei Bobrov
Andrei Bobrov 2017 年 5 月 23 日
out = M - diag(diag(M));
  2 件のコメント
Michael Chan
Michael Chan 2020 年 7 月 28 日
Not working if the diagonal is Inf or nan
tommsch
tommsch 2024 年 6 月 28 日 8:33
Also not working, if the matrix is not square

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

その他の回答 (3 件)

Stephen23
Stephen23 2017 年 4 月 19 日
編集済み: Stephen23 2017 年 4 月 19 日
Method one: indexing:
M(1:1+size(M,1):end) = 0
Method two: eye:
M.*~eye(size(M))
  1 件のコメント
Stephen23
Stephen23 2017 年 4 月 19 日
A strict interpretation of the question requires only diagonals equal to one get changed to zero: this is easy to implement with eye:
M.*~(eye(size(M)) & M==1)

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


Roger Stafford
Roger Stafford 2017 年 4 月 19 日
If your matrix M is not square and if you only want those diagonal elements changed to zero “if it is 1”, then you can do the following. Other diagonal elements not equal to one will remain unchanged. (Your description was perhaps a little ambiguous on this latter point.)
[m,n] = size(M);
d = 1:m+1:min(m^2,m*(n-1)+m);
f = find(M(d))==1;
M(d(f)) = 0;
  4 件のコメント
Stephen23
Stephen23 2022 年 1 月 4 日
@Hans Jakob Rivertz: not once you consider non-square matrices.
Zeina Abdullah
Zeina Abdullah 2022 年 1 月 5 日
@Stephen can you help me by try to answer the last question in my profile please

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


Christine Tobler
Christine Tobler 2017 年 5 月 23 日
編集済み: Christine Tobler 2017 年 5 月 23 日
If you are using the graph/digraph classes, you can also tell the constructor not to insert any self-loops for the diagonal elements:
g = graph(A, 'omitSelfLoops');

カテゴリ

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