Gabriel Machado
Gabriel Machado

Reputation: 155

Problems when plotting points in MATLAB

I'm having some problems when trying to plot two groups of points into a chart in MATLAB. I've created two matrices which represent the groups separately, one group of circles and the other of crosses. The outcome should be like the picture below:

enter image description here The code which creates the two groups is this:

circles = [1 1; 2 1; 2 2; 2 3; 2 4; 3 2; 3 3; 4 1; 4 2; 4 3];
crosses = [1 2; 1 3; 1 4; 2 5; 3 4; 3 5; 4 4; 5 1; 5 2; 5 3];

plot(circles, 'ro');
hold on
plot(crosses, 'b+');
hold off;
axis([0,6,0,6]);

But this code plots a messy chart, similar to the image below:

enter image description here

What could be wrong with the plotting?

Upvotes: 4

Views: 210

Answers (1)

anon
anon

Reputation:

Plot typically accepts two dimension arguments. If one is supplied, then the elements get plotted corresponding to their index.

PLOT Linear plot. PLOT(X,Y) plots vector Y versus vector X. If X or Y is a matrix, then the vector is plotted versus the rows or columns of the matrix, whichever line up. If X is a scalar and Y is a vector, disconnected line objects are created and plotted as discrete points vertically at X.

PLOT(Y) plots the columns of Y versus their index. If Y is complex, PLOT(Y) is equivalent to PLOT(real(Y),imag(Y)). In all other uses of PLOT, the imaginary part is ignored.

Various line types, plot symbols and colors may be obtained with PLOT(X,Y,S) where S is a character string made from one element from any or all the following 3 columns:

So since you need to provide both x and y separately, you could easily solve your problem like so:

circles = [1 1; 2 1; 2 2; 2 3; 2 4; 3 2; 3 3; 4 1; 4 2; 4 3];
crosses = [1 2; 1 3; 1 4; 2 5; 3 4; 3 5; 4 4; 5 1; 5 2; 5 3];

plot(circles(:, 1), circles(:, 2), 'ro');
hold on
plot(crosses(:, 1), crosses(:, 2), 'b+');
hold off;
axis([0,6,0,6]);

This solution is defining the x and y dimensions explicitly, so there should not be such a confusion with the plot and it will generate it exactly as you would like it to be.

Upvotes: 6

Related Questions