Defining a system of equations

3 views (last 30 days)
alpedhuez
alpedhuez on 26 Apr 2020
Commented: alpedhuez on 26 Apr 2020
In a previous post, a system of three ODE is set as
f = @(t,x) [-x(1)*x(2);x(1)*x(2)-x(2);x(2)]
But I want to define each equation in a separate line and then put all of the three together. Please advise.
  5 Comments
alpedhuez
alpedhuez on 26 Apr 2020
Edited: alpedhuez on 26 Apr 2020
Will run a set of ODEs here. So it will involve t.
Cesar García Echeverry
Cesar García Echeverry on 26 Apr 2020
ok call
function f=system(t,x)
f=[-x(1)*x(2);
x(1)*x(2)-x(2);
x(2)];
%Other option
% f(1)=-x(1)*x(2);
% f(2)=x(1)*x(2)-x(2);
% f(3)=x(2);
end
in other .m
clear;
clc;
close all
tic
%initial conditions
X0=[5; 5; 6];
%Step size
tf=30;
spam=[0 tf];
% dt=0.01;
%Método ODE (RK4)
options=odeset('RelTol',1e-4,'abstol',1e-4*ones(1,3));
[t,var]=ode45('system',spam,X0,options);
toc

Sign in to comment.

Accepted Answer

Ameer Hamza
Ameer Hamza on 26 Apr 2020
You can define it as an anonymous function. Creating a new file is not necessary.
First method
f = @(t,x) [-x(1)*x(2);
x(1)*x(2)-x(2);
x(2)];
Second method
f1 = @(t,x) -x(1)*x(2);
f2 = @(t,x) x(1)*x(2)-x(2);
f3 = @(t,x) x(2);
f = @(t,x) [f1(t,x);
f2(t,x);
f3(t,x)];
Both are equivalent.
  10 Comments
Ameer Hamza
Ameer Hamza on 26 Apr 2020
alpedhuez, yes. This is also equivalent to the options in my MATLAB.
alpedhuez
alpedhuez on 26 Apr 2020
So this data type @ allows to extend the domain of a function, which is reasonable.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!