# Executing a function in iterations

13 views (last 30 days)
Vira Roy on 31 Oct 2019
Commented: Vira Roy on 2 Nov 2019
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 have used a similar model equation in this question and just posting my attempted code here.
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 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

Walter Roberson on 31 Oct 2019
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 CommentsShowHide 7 older comments
Vira Roy on 2 Nov 2019
That clears everything Walter. Thanks a lot.

Sign in to comment.

### Categories

Find more on Switches and Breakers in Help Center and File Exchange

R2016a

### Community Treasure Hunt

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

Start Hunting!