Plotting a lattice with color coded nodes
8 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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');
else
plot(P(i,:), P(j,:), 'ro', 'MarkerFaceColor', 'r');
end
end
end
end
0 Kommentare
Akzeptierte Antwort
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.
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 Kommentare
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!