Executing a function in iterations
17 次查看(过去 30 天)
显示 更早的评论
Problem Statement: I have a system of differential equations in which i need to run a particular function for n iterations using preferably for loop. So basically i want my main script to run for all the different values of function.
I must mention that i have MATLAB 2016a in which i can't use function file in the main script.
function:MWE_fn.m
function rk1 = MWE_fn(t,y)
r2=0.5;b2=1;d_A=0.05;
c=0.5;
rk1(1)=r2*y(1)*(1-b2*y(1))-c*y(1)*y(2);
rk1(2)= A0(t)- d_A*y(2);
rk1=rk1(:);
end
function fa=A0(t)
if t>round(t)
fa=0.4;
else
fa=0;
end
end
Script: MWE_body.m
timerange= 0:0.5:360;
IC= [0.1,0];%initial conditions
for idx=1:length(timerange)-1
[tTemp,yTemp] =ode45(@(t,y) MWE_fn(t,y),timerange(idx:idx+1), IC);
t(idx) = tTemp(end);
y(idx,:) = yTemp(end,:);
IC = y(idx,:);
end
plot(t,y(:,1),'b');
hold on
plot(t,y(:,2),'r');
The above is an working example and i attempted to use a for loop in the function file but it showed me the error that i cannot define a function like that. What i want is that the following function, should run for different values of fa like from 0.1 to 1 and give plots for all those values separately.
function fa=A0(t)
if t>round(t)
fa=0.4;
else
fa=0;
end
end
Thank you for any help you can provide.
0 个评论
采纳的回答
Walter Roberson
2019-10-31
Your formulas are discontinuous. You cannot use any of the ode* functions for them. The discontinuities occur exactly at the integer times and nowhere else.
If I recall correctly you asked about the same system with different phrasing before, talking about a system that is driven the first half of the day and not driven the second half. You were advised then on how to proceed, and you were advised then that ode* routines evaluate at intermediate times, not just the boundaries you give for tspan. For example ode45 will try to evaluate at roughly t=1.08 and your test is not prepared that; 1.08>round(1.08) yes but 1.0>round(1.0) false but 1.0 is part of the first half day and so should be forced.
Do not use an if in an ode routine. Instead have two different functions, one with forcing and one without, and alternate calling them for the half days.
8 个评论
Walter Roberson
2019-11-2
why does the graph thickness keeps increasing?
Your graph scale is too small to see the oscillation clearly. Remember you drive for 1/2 and do not drive for 1/2 so you expect a rapid oscillation.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!