Question

I'm trying to plot 3 different lines in varying colors within a for loop. But only the last color in my loop is shown for all lines.

hold on

for N = [20, 200, 2000]
    f=@(t,u)cos(3*t)-sin(5*t)*u;
    a=0; b=4; ua=2;
    h=(b-a)/N;
    t=a+(0:N)*h; U=zeros(size(t));
    U(1)=ua;
    for n=1:N
        U(n+1)=U(n)+h*f(t(n),U(n));
    end
       for color=['r' 'g' 'b']
        plot(t,U,'color',color)
       end
end
Was it helpful?

Solution

The problem is that you're plotting each curve on top of itself three times, so that only the last color is shown. A simple way to fix this problem is to use a separate looping variable and two new vectors instead of the method you tried. I also moved some common definitions outside of your for loop:

hold on
NN = [20 200 2000];
colors=['rgb'];
f=@(t,u)cos(3*t)-sin(5*t)*u;
a=0; b=4; ua=2;
for jj = 1:3
    N = NN(jj);
    h=(b-a)/N;
    t=a+(0:N)*h;
    U=zeros(size(t));
    U(1)=ua;
    for n=1:N
        U(n+1)=U(n)+h*f(t(n),U(n));
    end
    plot(t,U,'color',colors(jj))
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top