필터 지우기
필터 지우기

Conditional variables with running ODE45

조회 수: 1 (최근 30일)
Brilliant Purnawan
Brilliant Purnawan 2020년 11월 19일
답변: Alan Stevens 2020년 11월 19일
Hi all, is it possible to call variables within an ODE45 and use if statements? So the general idea can be see in the code below, what I'm trying to do is that if the value of y(:,2) is greater than 0.3, than A will be 0.1 else, if its lower it will just run with a value of 0.1. Is this possible?
clear all, close all, clc
if y(:,2)>0.3
A = 0.2;
else
A = 0.1;
end
B = 0.1;
tspan = [0:4:200];
y0 = [0.95 0.05 0];
[t,y] = ode45(@(t,y)odefcn(y,A,B),tspan,y0);
figure(1)
hold on
plot(t,y(:,1),'-o')
plot(t,y(:,2),'-*')
plot(t,y(:,3),'-d')
function dydt = odefcn(y,A,B)
dydt = zeros(3,1);
dydt(1) = -A*y(2)*y(1);
dydt(2) = A*y(2)*y(1)-B*y(2);
dydt(3) = B*y(2);
end

채택된 답변

Alan Stevens
Alan Stevens 2020년 11월 19일
Yes, but rearrange the coding as follows:
tspan = [0:4:200];
y0 = [0.95 0.05 0];
[t,y] = ode45(@(t,y)odefcn(t,y),tspan,y0);
figure(1)
hold on
plot(t,y(:,1),'-o')
plot(t,y(:,2),'-*')
plot(t,y(:,3),'-d')
function dydt = odefcn(~,y)
if y(2)>0.3
A = 0.2;
else
A = 0.1;
end
B = 0.1;
dydt = zeros(3,1);
dydt(1) = -A*y(2)*y(1);
dydt(2) = A*y(2)*y(1)-B*y(2);
dydt(3) = B*y(2);
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by