Save array values in a for loop

1 回表示 (過去 30 日間)
omar rakgha
omar rakgha 2022 年 4 月 9 日
コメント済み: Jan 2022 年 4 月 9 日
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 件のコメント
Jan
Jan 2022 年 4 月 9 日
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.

サインインしてコメントする。

採用された回答

Alan Stevens
Alan Stevens 2022 年 4 月 9 日
Try replacing
error = max(abs(double(y1-z1(vx))))
with
error(i) = max(abs(double(y1-z1(vx))));
  1 件のコメント
omar rakgha
omar rakgha 2022 年 4 月 9 日
Thank u!!!!!!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeOrdinary Differential Equations についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by