Changing adjacent elements in matrix with input from user

조회 수: 6 (최근 30일)
ahmet karakoç
ahmet karakoç 2023년 4월 18일
답변: Walter Roberson 2023년 4월 18일
for i=1:n
for j=1:n
if matrixM(i,j)==0
matrixM(i+1,j)=-1;
matrixM(i,j+1)=-1;
matrixM(i-1,j)=-1;
matrixM(i,j-1)=-1;
end
end
end
Unrecognized function or variable 'n'.
I want to change elements to -1 which are adjacent (only lateral and vertical) to zero. How can I fix this code.

채택된 답변

Walter Roberson
Walter Roberson 2023년 4월 18일
You start j at 1, but you try to store into matrixM(i,j-1) . When j==1 then that would try to store into matrixM(i,0)
Likewise you start i at 1 but try to store into matrixM(i-1,j) which is matrixM(0,j)
You allow j to go to n but try to store into matrixM(i,j+1) . If n+1 is larger than the array, then you have a problem.
You have several different situations:
  • i is equal to 1. In that case, you must not access row i-1
  • i is equal to the number of rows in the array. In that case you must not access row i+1
  • j is equal to 1. In that case, you must not access column j-1
  • j is equal to the number of columns. In that case you must not access column j+1
  • otherwise neither i nor j are on the border and you can access the elements without restriction.
Now, you can do individual tests within your double-nested loop to be sure each location would be in range before doing the corresponding assignment. But there are other ways that might be more efficient.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by