フィルターのクリア

Substitue a diagonal matrix

3 ビュー (過去 30 日間)
AnnaMaria Accardo
AnnaMaria Accardo 2015 年 2 月 26 日
編集済み: sandhya 2015 年 2 月 27 日
Hi all, I'm trying to create a square matrix 9x9 where all the values are 9 and the diagonal is 0. Example:
0 9 9
9 0 9
9 9 0
I found a way to do it which is:
s(logical(eye(size(s)))) = 0
Is there an easy way to substitute a diagonal of a matrix (possibly without using [m n] = size(s) --> s[1:m]....) Thanks
  3 件のコメント
John D'Errico
John D'Errico 2015 年 2 月 26 日
Except, I find myself wondering if the problem is to create a 9x9 matrix of 9's, or a 3x3 matrix of 9's. The example shoed a 3x3 matrix, the words 9x9. :)
The difference is not important, just a matter of confusion.
AnnaMaria Accardo
AnnaMaria Accardo 2015 年 2 月 26 日
@John D'Errico is a 9x9 matrix but it will be very long if I had to write the entire matrix. It was just for an example. To be sure that the people will understand ;) :)

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

採用された回答

sandhya
sandhya 2015 年 2 月 26 日
The one line solution to your problem that strikes me (without using size function) is as under
9*(~eye(9,9))
Copy the above line of code and run in your command window. It gives the result you want.
Vote my answer if it was helpful....
  2 件のコメント
AnnaMaria Accardo
AnnaMaria Accardo 2015 年 2 月 26 日
Ok amazing answer. You will be the accepted answer. But can you explain to me what '~' means? Thanks
sandhya
sandhya 2015 年 2 月 27 日
編集済み: sandhya 2015 年 2 月 27 日
it is tilde operator whose fuction is negating the operation , that is convert 0' sto 1's and 1's to zeros. hope this answers your question

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

その他の回答 (2 件)

John D'Errico
John D'Errico 2015 年 2 月 26 日
編集済み: John D'Errico 2015 年 2 月 26 日
There are many ways of doing most anything in a tool like MATLAB.
To create the matrix you want to create, the very simplest one liner to do so is...
s = 9*~eye(3)
s =
0 9 9
9 0 9
9 9 0
Clearly this relies on the fact that your matrix was a very simple one, with constant off-diagonal elements, as well as constant (but different) diagonal elements. But the general idea is one that will work in other places too, so it is good to remember.
You did find a very reasonable way to zero out the diagonal of a matrix, or indeed to replace it too. I'll replace the diagonal of a 3x3 matrix of 9's with the numbers [1,2,3], just to show that you can use it for any general vector of elements.
s = 9*ones(3);
s(logical(eye(3))) = 1:3
s =
1 9 9
9 2 9
9 9 3
(Of course, vote for this answer if you found it useful.)

Sean de Wolski
Sean de Wolski 2015 年 2 月 26 日
And another:
~diag(1:3)*9

カテゴリ

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