Hi, I'm trying to make the rows equal to zero in a 3x3 matrix, but I don't get the result I need. Here
is my code:
>> M=magic(3)
M =
8 1 6
3 5 7
4 9 2
>> M(1:2:end)=0
M =
0 1 0
3 0 7
0 9 0
I found that using the following code I get the answer
>> M=magic(3);M(1:2:end,1:end)=0
M =
0 0 0
3 5 7
0 0 0
Could someone explain why the first code does not produce the correct result?
thanks

 Réponse acceptée

madhan ravi
madhan ravi le 14 Jan 2019
Modifié(e) : madhan ravi le 14 Jan 2019
M(1:2:end,:)=0
In your first code you are using linear indexing this is how matlab treats a matrix for instance
M= % the numbers are linear indices
1 4 7
2 5 8
3 6 9
% so all the odd indices are filled with zeros , see the link above.
% so
M=
0 4 0
2 0 8
0 6 0

5 commentaires

madhan ravi
madhan ravi le 14 Jan 2019
If my answer solved your question make sure to accept the answer else let know.
Pablo Pateti
Pablo Pateti le 15 Jan 2019
Hi Madhan,
Thank you very much for your help. Now I am clear on the differences between the different indexing logics in Matlab. I fixed the code and now I understand how it works. I appreciate you taking the time also to edit my question, adding the code to the correct format. It is my first time using the matlab forum, so I'm still getting to know how to post questions. Please let me know if there is something else I need to do in order to post correctly my answer. regards
madhan ravi
madhan ravi le 15 Jan 2019
Accept my answer since it helped you understand the concept.
Pablo Pateti
Pablo Pateti le 15 Jan 2019
I accepted the answer by clicking above, but i think it did not register that I accepted your answer. can you advice me on how to do this?
madhan ravi
madhan ravi le 15 Jan 2019
Modifié(e) : madhan ravi le 15 Jan 2019
Just click Accept this answer button , interesting you still couldn't figure it out (whereas you have done it before) so keep in mind that volunteers will have less interest in answering your questions in the future.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by