Search code examples
matlabplotmatlab-figure

Making a line plot of a set of values in MATLAB


I wish to obtain the line plot for the following vectors in MATLAB:

x=[0 0.6923 0.4615 0.2308 0.0769 1.0000];

and

y=[0 1.0000 1.0000 1.0000 0.6667 1.0000];

I used the command plot(x,y); to obtain the default line plot of MATLAB.

However, for some reason, the plot shows up like this: Incorrect Plot

The scatter plot of the values can be seen as follows: Scatter plot

Upon inspecting the scatter plot, it can be seen that the points fit a curve, but can be simply connected to the next neighbour by a line segment (The usual way MATLAB does) instead of the zig zag line.

Is there any way to fix Figure 1?

And, Why does MATLAB end up connecting two different points that are not in succession ?


Solution

  • The plot() function does draw the line in exactly the order you specified your points. I guess you are looking for a plot with a line starting at the left most point continuing until the right most point. To reach this goal you have to sort your points by ascending x-values.

    x=[0    0.6923    0.4615    0.2308    0.0769    1.0000];
    y=[0    1.0000    1.0000    1.0000    0.6667    1.0000];
    [x,idx] = sort(x);
    y = y(idx);
    plot(x,y,'o-');
    disp(x);
    disp(y);
    

    This produces the following output:

    0.00000 0.07690 0.23080 0.46150 0.69230 1.00000

    0.00000 0.66670 1.00000 1.00000 1.00000 1.00000

    enter image description here