Fill in matrix using nested loop

6 views (last 30 days)
Hello,
I am struggling to create the xyFit matrix below.
What I am trying to do is to fill in "0" when xx is below the xcrit value (3) and to fill in "1" when xx is at or above the xcrit value.
Here is what I have come up with so far:
Cap = 10;
xcrit = 3;
xx = Cap;
yy = Cap;
xyprob = ones(xx,yy)*0.1; %probability individual A encounters opponent B
xyFit = zeros(xx,yy); %building fitness matrix
for ii = 1:xx
for jj = 1:yy
if ii == 1:(xcrit-1)
xyFit(ii,jj)==0
else
xyFit(ii,jj)== 1
end
end
end
Any help would be greatly appreciated!

Accepted Answer

Star Strider
Star Strider on 4 Aug 2020
I am not certain what you want to do.
Try this:
Cap = 10;
xcrit = 3;
xx = Cap;
yy = Cap;
xyprob = ones(xx,yy)*0.1; %probability individual A encounters opponent B
xyFit = zeros(xx,yy); %building fitness matrix
for ii = 1:xx
for jj = 1:yy
if ii < xcrit
xyFit(ii,jj) = 0;
else
xyFit(ii,jj) = 1;
end
end
end
Theere are probably easier ways to do what you want (for example using ‘logical indexing’). Aside from that, note that the double-equal == is for the logical comparison for equailty, not for assignment. To assign a value to a variable, use only =.
.
  2 Comments
Macie Smith
Macie Smith on 4 Aug 2020
I'm not sure why I didn't think of using "<"... been looking at it for too long I guess. Thank you very much! Working now
Star Strider
Star Strider on 4 Aug 2020
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!