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))));

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by