Replacing elements in a matrix with the same row and column index
5 views (last 30 days)
Show older comments
Sanwal Yousaf
on 20 Jul 2015
Commented: Walter Roberson
on 21 Jul 2015
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)
0 Comments
Accepted Answer
Walter Roberson
on 20 Jul 2015
s_matrix(1:s_data+1:end) = 1;
2 Comments
Walter Roberson
on 21 Jul 2015
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.
More Answers (0)
See Also
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!