Save array values in a for loop
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
omar rakgha
am 9 Apr. 2022
Kommentiert: Jan
am 9 Apr. 2022
Hi!
I am trying to plot the error of a numerical ODE solver as the step size changes, but only the last value for error saves after the for loop (lines 22-23). How can I change this so it plots the error for each step change in i. Thank you in advance
clc;clear all;close all; format compact;
A = 2;Kc = 1;Ti = 0.1;
y1(1) = 0;
y2(1) = 2;
t(1) = 0;
syms x z1(x) z2(x);
ode1 = diff(z1,x)==z2(x);
ode2 = A*diff(z2,x)+Kc*z2(x)+Kc*z1(x)/Ti==0;
cond1 = z1(0)==0;
cond2 = z2(0)==2;
[z1(x),z2(x)] = dsolve([ode1,ode2],[cond1,cond2]);
for i = linspace(100,1000,10)
DeltaT = 50/i;
for n = 1:i
y2(n+1) = y2(n)-((1/A)*(Kc*y2(n)+Kc*y1(n)/Ti))*DeltaT;
y1(n+1) = y1(n)+y2(n)*DeltaT;
t(n+1) = t(n)+DeltaT;
end
vx = linspace(0,50,i+1);
error = max(abs(double(y1-z1(vx))))
end
plot(i,error,'x')
1 Kommentar
Jan
am 9 Apr. 2022
Some hints:
clear all removes all loaded functions from the memory. Reloading them from the slow disk wastes time and offers no advantage.
Avoid shadowingof important Matlab functions by variables. After "error=1" you cannot use the error() function anymore.
Akzeptierte Antwort
Alan Stevens
am 9 Apr. 2022
Try replacing
error = max(abs(double(y1-z1(vx))))
with
error(i) = max(abs(double(y1-z1(vx))));
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Ordinary Differential Equations finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!