Subplot in a for loop with different graphs

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

Réponses (2)

KSSV
KSSV le 9 Juil 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
Alan Stevens
Alan Stevens le 9 Juil 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

Catégories

En savoir plus sur Number games dans Centre d'aide et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by