MATLAB: How to add a legend to the plot

differential equationsivplegendsplot

%Define the variables using syms - syms creates symbolic variables
syms y(t) y0
%define the ordinary differential equation
ode = diff(y,t) == cos(t^2);
%solve the differential equation using dsolve
ysol = dsolve(ode,y(0)==y0);
%Create a figure called Task 1
figure ('Name','Task 1')
%Pick 3 different initial conditions for which the solution exists
%Conditions are the y values (y values are 1, 1.5, and 3 at varying t
%values. See the t values below.
conds = [1 1.5 3]'; %some values of y0
f = matlabFunction(subs(ysol,y0,conds));
t = linspace(0,50);
y = f(t);
%plotting the 3 equations
plot(t,y,'linewidth',2)
title('Symbolic Solutions')
xlabel('t')
ylabel('y(t)')
grid on

Best Answer

To add the legend, either use sprintfc (undocumented although quite useful):
lgndc = sprintfc('IC = %.1f',conds);
legend(lgndc, 'Location','E')
or compose:
lgndc = compose('IC = %.1f',conds);
legend(lgndc, 'Location','E')
both produce the same result.
Put these lines after your ‘grid on’ call.