How do you use the legend function in MATLAB?

In MATLAB, you can use the legend function to create a legend, identifying the content represented by each data series or curve.

There are two common ways to use the legend function:

  1. Before drawing the curves, create a legend by passing a string array to the legend function. For example, if you have two curves labeled as “Data 1” and “Data 2”, you can create the legend using the following code:
x = 1:10;
y1 = 2*x;
y2 = 3*x;
plot(x, y1, 'r', x, y2, 'b');
legend('Data 1', 'Data 2');

This code will plot two curves in red and blue, displaying “Data 1” and “Data 2” in the legend.

  1. After drawing the curves, variables can be used to label each data series and input these variables into the legend function. For example, using the curve data above, you can create a legend with the following code.
x = 1:10;
y1 = 2*x;
y2 = 3*x;
plot(x, y1, 'r');
hold on;
plot(x, y2, 'b');
legend('Data 1', 'Data 2');

Please note that we are using the “hold on” command to keep the plot window open, allowing us to plot multiple lines on the same graph. We then use the labels of each data series as inputs for the legend function.

You can customize the appearance of the legend by choosing options like location, font size, and color, no matter which method you choose. For more information, refer to the relevant section of the legend function in the MATLAB documentation.

bannerAds