while sum(Master1(:)) < 400
scan = ((r-1):(r+1):(c-1):(c+1));
This will most likely not do, what you expect:
The colon operator is defined with two : only: a:b:c is the vector from a to c in steps of b. This replies a vector. In the next step this vector is used as 1st input for the next colon operator:
((r-1):(r+1):(c-1)) : (c+1)
If a vector is used as input of the colon operator, only the first element is considered and the rest is ignored. Therefore your code is equivalent to:
What is the purpose of the variable scan? Do you want to collect indices or the values of the matrix?
The problem causing the infinite loop, is that the body of the loop does not change the condition. If sum(Master1(:)) < 400 is true initially, this will never change, because Master1 is not modified inside the loop.
Why do you use the copy temp of Master1 and not the data directly? Maybe you want:
scan = M((r-1):(r+1), (c-1):(c+1));