MATLAB Answers

Subplot in a for loop with different graphs

9 views (last 30 days)
Vincent Lemmens
Vincent Lemmens on 9 Jul 2020
Answered: Alan Stevens on 9 Jul 2020
Hello, I would like to have my program plot my outputs in 2 different figures. Two [1,5] subplots, but my graph is changing within every iteration. Please help...
clear all;
close all;
clc;
%% Input
a = 0;
b = 3;
yt = @(t) 5.*exp(-t).*(-1 + sin(10.*t));
dydt = @(t,y) -y + 50*cos(10*t)*exp(-t);
y0 = -5;
%% Midpoint toepassen
for n = [8 16 32 64 128]
[t,y] = midpoint(dydt,a,b,y0,n);
ytwaarde = yt(t);
figure();
plot(t,y)
hold on
fplot(yt, [a b])
title(strcat('Grafiek bij N =',int2str(n)));
legend('Benadering van yt' ,'yt','Location', 'northeastoutside');
figure
plot(t,abs(ytwaarde - y))
title(strcat('De fout bij N = ', int2str(n)));
set(gca, 'YScale', 'log')
end
%% Functies
function [t,w] = midpoint(f,a,b,y0,n)
h = (b-a)/n;
t = a:h:b;
w = ones(size(t));
w(1) = y0;
for n = 2:length(t)
w(n) = w(n-1) + h*f(t(n-1) + h/2, w(n-1) + (h/2)*f(t(n-1),w(n-1)));
end
end

  0 Comments

Sign in to comment.

Answers (2)

KSSV
KSSV on 9 Jul 2020
for i = 1:5
figure(1)
subplot(5,1,i)
plot(rand(1,10))
figure(2)
subplot(5,1,i)
plot(rand(1,10))
endfor

  0 Comments

Sign in to comment.


Alan Stevens
Alan Stevens on 9 Jul 2020
Something like this perhaps (though the labelling could be tidied up!):
a = 0;
b = 3;
yt = @(t) 5.*exp(-t).*(-1 + sin(10.*t));
dydt = @(t,y) -y + 50*cos(10*t)*exp(-t);
y0 = -5;
%% Midpoint toepassen
N = [8 16 32 64 128];
for i = 1:5
n = N(i);
[t,y] = midpoint(dydt,a,b,y0,n);
ytwaarde = yt(t);
figure(1);
subplot(5,1,i)
plot(t,y)
hold on
fplot(yt, [a b])
text(2,min(y)/2,strcat('Grafiek bij N =',int2str(n)));
% legend('Benadering van yt' ,'yt','Location', 'northeastoutside');
figure(2)
subplot(5,1,i)
plot(t,abs(ytwaarde - y))
text(0.1, mean(abs(ytwaarde - y))/4,strcat('De fout bij N = ', int2str(n)));
set(gca, 'YScale', 'log')
end
%% Functies
function [t,w] = midpoint(f,a,b,y0,n)
h = (b-a)/n;
t = a:h:b;
w = ones(size(t));
w(1) = y0;
for n = 2:length(t)
w(n) = w(n-1) + h*f(t(n-1) + h/2, w(n-1) + (h/2)*f(t(n-1),w(n-1)));
end
end

  0 Comments

Sign in to comment.

Products