Making odd rows equal to zero in a 3x3 Matrix

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

 Accepted Answer

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 Comments

If my answer solved your question make sure to accept the answer else let know.
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
Accept my answer since it helped you understand the concept.
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?
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.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!