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

 채택된 답변

madhan ravi
madhan ravi 2019년 1월 14일
편집: madhan ravi 2019년 1월 14일

2 개 추천

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

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?
madhan ravi
madhan ravi 2019년 1월 15일
편집: madhan ravi 2019년 1월 15일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

태그

질문:

2019년 1월 14일

편집:

2019년 1월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by