Plotting a lattice with color coded nodes

9 Ansichten (letzte 30 Tage)
Bill Symolon
Bill Symolon am 3 Mär. 2017
Kommentiert: Bill Symolon am 4 Mär. 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');
plot(P(i,:), P(j,:), 'ro', 'MarkerFaceColor', 'r');

Akzeptierte Antwort

David J. Mack
David J. Mack am 3 Mär. 2017
Bearbeitet: David J. Mack am 3 Mär. 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
  2 Kommentare
Bill Symolon
Bill Symolon am 4 Mär. 2017
That's awesome! Thanks, David.
Bill Symolon
Bill Symolon am 4 Mär. 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!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)


Mehr zu Mathematics finden Sie in Help Center und File Exchange


Community Treasure Hunt

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

Start Hunting!

Translated by