Coding Ref

How to plot a line in MATLAB

How to plot a line in MATLAB

To plot a line in MATLAB, you can use the plot function.

The plot function takes two arguments, representing the x-coordinates and y-coordinates of the data points. For example, to plot the points (1,2), (3,4), and (5,6), you could use the following commands:

x = [1 3 5];
y = [2 4 6];
plot(x, y)

The plot function connects the data points with a line by default. This line is called a line plot. The line plot can help to visualize the trend of the data and make predictions about future values.

In addition to the x- and y-coordinates, the plot function also accepts a number of optional arguments that allow you to customize the appearance of the line plot. For example, you can specify the color, line style, and marker type using the 'Color', 'LineStyle', and 'Marker' properties.

Here is an example that creates a line plot with a red dashed line and circular markers:

x = [1 3 5];
y = [2 4 6];
plot(x, y, 'Color', 'r', 'LineStyle', '--', 'Marker', 'o')

You can also add labels, titles, and a legend to your line plot. For example, the following commands will add a title, axis labels, and a legend to the previous plot:

x = [1 3 5];
y = [2 4 6];
plot(x, y, 'Color', 'r', 'LineStyle', '--', 'Marker', 'o')
title('Line Plot Example')
xlabel('x')
ylabel('y')
legend('data')

Labeling a line

You can add labels to a line plot in MATLAB using the xlabel, ylabel, and title functions. The xlabel and ylabel functions add labels to the x-axis and y-axis of the plot, respectively. The title function adds a title to the plot.

Here is an example of how to use the xlabel, ylabel, and title functions to add labels to a line plot:

x = 0:0.1:10;
y = sin(x);
plot(x, y)
xlabel('x')
ylabel('sin(x)')
title('Sine Wave')

Conclusion

In MATLAB, the plot function is used to create a graph of data. The plot function takes two arguments, representing the x-coordinates and y-coordinates of the data points.

You'll also like

Related tutorials curated for you

    Plot markers in MATLAB

    How to plot points in MATLAB

    MATLAB linspace

    How to create a surface plot in MATLAB

    How to create a scatter plot in MATLAB

    How to plot colors in MATLAB

    How to create a 3D plot in MATLAB

    MATLAB subplot

    How to plot a Bode in MATLAB

    How to plot a line in MATLAB

    How to plot a legend in MATLAB