How can I check adjacent matrix values for a value?
11 views (last 30 days)
Show older comments
function e=evosim()
board=(zeros(12,12));
pop=1;
charac=([1, 0]);
cloc=[];
for i=1:pop %%Population generator%%
popcount=1;
a=randi([1,12]);
b=randi([1,12]);
if board(a,b)==0
board(a,b)=charac(1);
cloc=[b a popcount; cloc]
end
end
for i=1:10 %%Food generator%%
a=randi([1,12]);
b=randi([1,12]);
if board(a,b)==0
board(a,b)=2;
end
end
e=board;
for i=1:pop
xcord=cloc(i,1);
ycord=cloc(i,2);
if board(xcord-1,ycord)==2
end
Here's my code so far: basically, I have a blank 12x12 matrix, and randomly place 1's and 2's. I want to check the 8 squares around the 1, and the x and y coordinates of any 1s are stored in cloc. After it checks, I want the 1 to 'jump' to the location of where the 2 was.
I think I could do it by checking for (xcord+-1, ycord+-1,) etc, and recording the coordinates of the matrix 1s. However, I was wondering if there was a more efficient way of doing this.
I am new to matlab as well, so any suggestions are more than welcome in improving my code! Thanks!
0 Comments
Accepted Answer
Matt J
on 7 Nov 2020
I don't understand the rules of evolution of the board that you described. However, an efficient way to gather all the 8-neighbor groups for subsequent analysis is as follows. Here, I've used a 4x4 board size for illustration,
n=4; %board size
[I,J,dI,dJ]=ndgrid(1:n,1:n,-1:1,-1:1);
I=reshape(I+dI,[],9); clear dI
J=reshape(J+dJ,[],9); clear dJ
valid=(I>=1 & I<=n) & (J>=1 & J<=n);
I(~valid)=nan;
J(~valid)=nan;
lookup=sub2ind([n,n],I,J);
lookup(~valid)=1;
lookup(:,5)=[];
valid(:,5)=[];
mask=double(valid); mask(~valid)=nan;
The key results of this are lookup and mask. You would compute them only once and pass them to your function for repeated use. You use them as follows, to form a matrix whose rows are the neighbors of successive locations on the board. The NaNs indicate nieghbors outside the boundaries of the board.
board=rand(n),
neighbors = board(lookup).*mask
2 Comments
Matt J
on 7 Nov 2020
You're quite welcome. Please Accept-click the answer if and when you decide it gives you what you need.
More Answers (0)
See Also
Categories
Find more on Oil, Gas & Petrochemical 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!