9 views (last 30 days)

Hello all. Probably quite an easy problem but I am stuck.

f=@(t,u)-u+sin(5*t)+cos(2*t);

a=0; b=5; ua=2; % begynnelsevillkor

t=linspace(a,b,15); u=linspace(-2,2,15);

riktningsfaelt(f,t,u);

N=10; h=(b-a)/N; %steglängd

T=linspace(a,b,N+1); U=zeros(size(T));

U(2)=ua; %enligt begynnelsevillkor

for n=1:N

U(n+1)=U(n)+h*f(T(n),U(n)); % Eulers metod

end

plot(T,U)

So what I want to do is plot but with different N values in the same figure. I have tried "hold on" then set a new N value but it doesn't work. Lets say I want to plot N=10 and N=100 in the same figure, how do I do that??

Mischa Kim
on 10 Nov 2017

Edited: Mischa Kim
on 10 Nov 2017

Joakim, is this what you had in mind?

f=@(t,u)-u+sin(5*t)+cos(2*t);

a=0; b=5; ua=2; % begynnelsevillkor

t=linspace(a,b,15); u=linspace(-2,2,15);

% riktningsfaelt(f,t,u);

for N = 10:10:100

h=(b-a)/N; %steglängd

T=linspace(a,b,N+1);

U=zeros(size(T));

U(2)=ua; %enligt begynnelsevillkor

for n=1:N

U(n+1)=U(n)+h*f(T(n),U(n)); % Eulers metod

end

plot(T,U)

hold on

end

Mischa Kim
on 10 Nov 2017

Simple enough. Replace the for command by

for N = [10,100,1000]

The code in my first answer above creates essentially the same graph, just with 10 plots vs 3.

Rik
on 11 Nov 2017

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/366136-plot-multiple-subintervals-in-one-figure#comment_503071

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/366136-plot-multiple-subintervals-in-one-figure#comment_503071

## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/366136-plot-multiple-subintervals-in-one-figure#comment_503183

⋮## Direct link to this comment

https://www.mathworks.com/matlabcentral/answers/366136-plot-multiple-subintervals-in-one-figure#comment_503183

Sign in to comment.