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

16 次查看(过去 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 个评论
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 中查找有关 Operating on Diagonal Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by