Why does calling the legend function with multiple outputs throw a warning in MATLAB R2024b?

When I use the "legend" function in MATLAB R2024b, I encounter the below warning:
Warning: Calling legend with multiple outputs will not be supported in a future release
I see this after running the following script:
figure; hold on;
x = linspace(0, 2*pi, 200);
p(1) = plot(x, sin(x), 'LineWidth', 1);
p(2) = plot(x, cos(x), 'LineWidth', 1);
p(3) = plot(x, sin(2*x), 'LineWidth', 1);
hold off
[~, legObjs] = legend(p, {'Sine', 'Cosine', 'Sin 2x'}, 'Location', 'best');
Why does this warning occur and how should I use the "legend" function to avoid this issue while maintaining current functionality?

 Accepted Answer

Calling "legend" with multiple outputs may not be supported in releases after MATLAB R2024b.
[lgd,icons,plots,txt] = legend(...)
This creates a legend that does not support some functionality. For example, you cannot add a title to the legend or specify the number of legend columns. Also, the legend does not automatically update when you add or remove data series from the axes.
To avoid this warning and leverage additional legend features, consider using the below syntax in MATLAB R2024b and modify the Legend Properties to preserve current functionality
lgd = legend(...)
You can port the script you provided to MATLAB R2024b syntax with the following script:
figure; hold on;
x = linspace(0, 2*pi, 200);
p(1) = plot(x, sin(x), 'LineWidth', 1, 'DisplayName','Sine');
p(2) = plot(x, cos(x), 'LineWidth', 1, 'DisplayName','Cosine');
p(3) = plot(x, sin(2*x), 'LineWidth', 1, 'DisplayName','Sin 2x');
hold off
lgd = legend(p, 'Location','best');

1 Comment

Note:
Some things that used to be possible by specifying a second output to legend(), are simply no longer possible from R2025a. Some of the behaviours have work-around functionality, but other possibilities simply cannot happen any more.

Sign in to comment.

More Answers (0)

Products

Release

R2025b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!