yankeefan11
yankeefan11

Reputation: 485

Solving coupled nonlinear differential equations

I have a differential equation that is as follows:

%d/dt [x;y] = [m11 m12;m11 m12][x;y]
mat = @(t) sin(cos(w*t))
m11 = mat(t) + 5 ; 
m12 = 5;
m21 = -m12 ;
m22 = -m11 ;

So I have that my matrix is specifically dependent on t. For some reason, I am having a super difficult time solving this with ode45. My thoughts were to do as follows ( I want to solve for x,y at a time T that was defined):

t = linspace(0,T,100) ; % Arbitrary 100
x0 = (1 0); %Init cond
[tf,xf] = ode45(@ddt,t,x0)

function xprime = ddt(t,x)
ddt = [m11*x(1)+m12*x(2) ; m12*x(1)+m12*x(2) ]
end

The first error I get is that

Undefined function or variable 'M11'.  

Is there a cleaner way I could be doing this ?

Upvotes: 1

Views: 660

Answers (2)

Lutz Lehmann
Lutz Lehmann

Reputation: 26040

One glaring error is that the return value of function ddt is xprime, not ddt. Then as mentioned in the previous answer, mm1 at the time of definition should give an error as t is not defined. But even if there is a t value available at definition, it is not the same t the procedure ddt is called with.

mat = @(t) sin(cos(w*t))
function xprime = ddt(t,x)
    a = mat(t) + 5 ; 
    b = 5;
    ddt = [ a, b; -b, -a]*x
end

should work also as inner procedure.

Upvotes: 0

gnovice
gnovice

Reputation: 125874

I'm assuming you're running this within a script, which means that your function ddt is a local function instead of a nested function. That means it doesn't have access to your matrix variables m11, etc. Another issue is that you will want to be evaluating your matrix variables at the specific value of t within ddt, which your current code doesn't do.

Here's an alternative way to set things up that should work for you:

% Define constants:
w = 1;
T = 10;
t = linspace(0, T, 100);
x0 = [1 0];

% Define anonymous functions:
fcn = @(t) sin(cos(w*t));
M = {@(t) fcn(t)+5, 5; -5 @(t) -fcn(t)-5};
ddt = @(t, x) [M{1, 1}(t)*x(1)+M{2, 1}*x(2); M{1, 2}*x(1)+M{2, 2}(t)*x(2)];

% Solve equations:
[tf, xf] = ode45(ddt, t, x0);

Upvotes: 2

Related Questions