Replacing elements in a matrix with the same row and column index
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sanwal Yousaf
el 20 de Jul. de 2015
Comentada: Walter Roberson
el 21 de Jul. de 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 comentarios
Respuesta aceptada
Walter Roberson
el 20 de Jul. de 2015
s_matrix(1:s_data+1:end) = 1;
2 comentarios
Walter Roberson
el 21 de Jul. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!