Plotting a lattice with color coded nodes

조회 수: 6 (최근 30일)
Bill Symolon
Bill Symolon 2017년 3월 3일
댓글: Bill Symolon 2017년 3월 4일
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

채택된 답변

David J. Mack
David J. Mack 2017년 3월 3일
편집: David J. Mack 2017년 3월 3일
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
Bill Symolon
Bill Symolon 2017년 3월 4일
That's awesome! Thanks, David.
Bill Symolon
Bill Symolon 2017년 3월 4일
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!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Exploration and Visualization에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by