Replacing elements in a matrix with the same row and column index

4 ビュー (過去 30 日間)
Sanwal Yousaf
Sanwal Yousaf 2015 年 7 月 20 日
コメント済み: Walter Roberson 2015 年 7 月 21 日
I am trying to create an alternative to the diagonal function. In doing so, i am creating a function using a user input for zeros. I want to replace the elements in that matrix that have the same row and column number with 1 instead of zeros. So element with the (row, column) location of say (1,1), (2,2), (3,3) and so on would be replaced with a 1 instead of a 0. Is there a way that i could do that.
This is my code so far,
function [matrix] = identity(s)
s= inputdlg('What is the scalar for matrix creation','Scalar value',[1, 40]);
data_s = str2num(s{:})
s_matrix= zeros(data_s)

採用された回答

Walter Roberson
Walter Roberson 2015 年 7 月 20 日
s_matrix(1:s_data+1:end) = 1;
  2 件のコメント
Sanwal Yousaf
Sanwal Yousaf 2015 年 7 月 21 日
Thanks a lot. Would you be kind enough to explain how this is working??
Walter Roberson
Walter Roberson 2015 年 7 月 21 日
MATLAB linear indexing numbers down the columns. There are s_data entries in each column. If you consider index 1, the array at (1,1), linear 1+s_data correspond to the array at (1,2). The entry below that one, the second element of the diagonal, would then be at 1+s_data+1 which is a difference of s_data+1 from the original index. The entry to the right of that would be 1+s_data+1+s_data so the third element of the diagonal would be at 1+s_data+1+s_data+1 which is a difference of s_data+1 from the previous diagonal entry. We can then see that if we start at 1, and add s_data+1 each time, we follow the diagonal entries.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by