MATLAB: Need assistance updating a Matrix While code is iterating

matrix

The Idea behind my code is to take an empty matrix and, based on a series of subroutines, refill it with new values. The issue I'm having is that rather than storing the new values in the matrix and testing this new matrix the code is erasing and overwriting any previous alterations to the matrix. When the code does loop it hits its recursion limit when the goal is to simply fill the empty spaces in the M(x) matrix.
n=5; %matrix size
M=zeros(n);%matrix of all zeros that is being updated
I=1; %number of iterations
C=zeros(size(M));%matrix of random numbers that determine the directional value assigned to each position
D=zeros(size(M));%matrix of positional values
for y=randi(n),x=randi(n);
if M(x,y)==0
C(x,y)=NumberGenerator; %determines what random value is assigned to the matrix postion
if C(x,y)<.2
M(x,y)=0;
D(x,y)=0;
Test; %Name of this code, meant to loop this process
elseif C(x,y)>.2
M(x,y)=1;
MatrixGenV2; %subroutine that generates a directional value at each position based on C(x,y)
BoundaryCondition; %Boundary condition I've placed on the matrix
Test;
end
elseif M(x,y)>0
Test;
end
end
Keep in mind I'm very new to Matlab so if my code isn't as streamlined as it can be that's why. Thank you in advance for any help.

Best Answer

There are several problems in this for-loop.
for y=randi(n),x=randi(n);
This is actually executed as two lines of code the first: y=randi(n) and the second: x=randi(n). What I think you want to do is execute these two lines within a loop but I don't know what you're loop over. I noticed your variable "I" isn't used and there's comment "number of iterations" so perhaps you want.
for j = 1:I
y=randi(n),
x=randi(n);
...
end
Since x and y are random integers, you'll likely continue to overwrite values in the matricies that use X and Y as indices since it's possible for the same number of be chosen randomly. One way around that is to use randsample() which can sample integers without replacement.