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

조회 수: 4 (최근 30일)
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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by