MATLAB Answers

Plotting a lattice with color coded nodes

84 views (last 30 days)
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');
plot(P(i,:), P(j,:), 'ro', 'MarkerFaceColor', 'r');


Sign in to comment.

Accepted Answer

David J. Mack
David J. Mack on 3 Mar 2017
Edited: David J. Mack on 3 Mar 2017
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.
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:
Greetings, David


Bill Symolon
Bill Symolon on 4 Mar 2017
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.

More Answers (0)

Sign in to answer this question.