MATLAB R2017a Legend displays wrong color when plotting multiple entries

When I execute the following code,
f_0 = 1;
x = [0:0.1:10];
fhandle = @(x) 2*x;
dx = 0.1;
f = RK4(fhandle, x, f_0);
freal = @(x) x.^2 + 1;
feuler = ode_euler(x,f_0);
figure
plot(x,f,x,freal(x),x,feuler);
legend('4th-order Runge-Kutta','Exact','Euler')
xlabel("x")
ylabel("f(x)")
title("Runge-Kutta, Exact, Euler solutions to df/dx = 2x")
function f = RK4(fhandle, x, f_0)
%dx = 0.1;
n = size(x);
dx = (x(n)-x(1))/n;
f(1) = f_0;
for i=1:n-1
v1 = dx*fhandle(f(i));
v2 = dx*fhandle(f(i)+dx/2);
v3 = dx*fhandle(f(i)+dx/2);
v4 = dx*fhandle(f(i)+dx);
f(i+1) = f(i) +1/6*(v1+2*v2+2*v3+v4);
end
end
function f = ode_euler(x,f_0)
delta_x = x(2)-x(1);
l_x=length(x);
f=zeros(1,l_x);
f(1)=f_0;
for ii=1:(l_x-1)
f(ii+1) = f(ii) + delta_x*2*x(ii);
end
end
Legend displays the wrong color lines for each plot. Assigning 3 separate plots doesn't help my situation. I have also tried assigning colors to the plots, as well as just about anything I can think of. When I assign colors to the individual plots, they each get the proper color but the legend displays each line as the color of the first graph.
How can I properly make the legend to display 3 different, correct, colors for my 3 plots on the figure?

Answers (1)

Hi Josh, I tackled the same bug, and finally fixed it by re-ordering the arguments to plot(); of course, you should change the arguments to legend() accordingly.
For instance, in your code, you may try to change your calls to plot() and legend() to:
plot(x,f,x,feuler,x,freal(x));
legend('4th-order Runge-Kutta','Euler' ,'Exact')
or to another permutation, until it works. Hope it helps.

Products

Asked:

on 8 Mar 2018

Edited:

on 12 Jun 2018

Community Treasure Hunt

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

Start Hunting!