MATLAB Answers

0

Plotting a lattice with color coded nodes

Asked by Bill Symolon on 3 Mar 2017
Latest activity Commented on by Bill Symolon on 4 Mar 2017
I'm trying to plot a 2-D lattice with node values randomly assigned as either 1 or 2. I would like all nodes with values equal to 1 to plot in blue and all nodes with values equal to 2 to plot in red. The code I'm using plots all nodes in either red or blue but doesn't have the colors scattered throughout the plot the way I expected. Also, the plot seems to be missing two nodes down in the bottom left corner. I appreciate any help you can provide.
if true
% Generate the initial 50 by 50, 2-dimensional lattice
[n1,n2] = meshgrid(0:50);
P = [ n1(:) n2(:) ].';
% Randomly assign initial node values
for i = 1:51
for j = 1:51
P(i,j) = randi(2);
if P(i,j) == 1;
plot(P(i,:), P(j,:), 'bo', 'MarkerFaceColor', 'b');
else
plot(P(i,:), P(j,:), 'ro', 'MarkerFaceColor', 'r');
end
end
end
end

  0 Comments

Sign in to comment.

Tags

1 Answer

Answer by David J. Mack on 3 Mar 2017
Edited by David J. Mack on 3 Mar 2017
 Accepted Answer

Hey Bill!
% Generate the random values on the 50x50, 2-dimensional lattice directly
% using X = randi(imax,sz1,...,szN) syntax.
P = randi(2,51,51); % 0:50 -> 51 elements
% Create figure with axes on hold, so successive plot commands will add and
% not replace. Also add zero-based axis limits and make the axes square.
figure;
axes('NextPlot','add','XLim',[0 size(P,1)-1],'YLim',[0 size(P,2)-1]);
axis square;
% Use linear indexing to find the values to plot.
isOne = P==1;
[i1,j1] = ind2sub(size(P),find( isOne)); % ones
[i2,j2] = ind2sub(size(P),find(~isOne)); % twos
% Plot (can also be combined in one call). Subtract 1 to get zero-based ids.
plot(i1-1, j1-1, 'bo', 'MarkerFaceColor', 'b');
plot(i2-1, j2-1, 'ro', 'MarkerFaceColor', 'r');
An even simpler option is to use imagesc:
P=randi(2,51,51);
imagesc(P)
Greetings, David

  2 Comments

That's awesome! Thanks, David.
David, I hope I can impose on you again. I haven't even been able to get a draft code working for the next step, so I'm going to try to explain my goal.
Now that I have the initial lattice, I need to evaluate the 4 neighboring nodes: above, below, left, right (not diagonal). For the nodes at the corners and edges, they would only evaluate the 2 or 3 neighbors that they do have. If two or more of the neighboring nodes have a different value (eg, if the middle node = 1 and at least two of the neighboring nodes = 2, then the middle node will change its value to equal the prevailing "opinion." I need to iterate this process for a number of time steps (say 100) to observe the clustering effect.
If you have any ideas, I would greatly appreciate your help!

Sign in to comment.