필터 지우기
필터 지우기

Executing a function in iterations

조회 수: 5 (최근 30일)
Vira Roy
Vira Roy 2019년 10월 31일
댓글: Vira Roy 2019년 11월 2일
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.

채택된 답변

Walter Roberson
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
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.
Vira Roy
Vira Roy 2019년 11월 2일
That clears everything Walter. Thanks a lot.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by