Question

I have defined a function using matlabFunction. Here is the code:

matlabFunction([a16;-((1+x16^2)/(2*x16))*a16],'vars',{x16,[a16]},'file','DE_19') 

which seemed to work. However, when I try to use ode45 to solve the differential equation defined by matlabFunction, I get an error. Here is the code:

[x,y] = ode45(@(x16,Y) DE_19(x16,Y),[1,11],[2,7,5]);

The error I get is

   Error using odearguments (line 93)
@(X16,Y)DE_19(X16,Y) returns a vector
of length 6, but the length of
initial conditions vector is 3. The
vector returned by
@(X16,Y)DE_19(X16,Y) and the initial
conditions vector must have the same
number of elements.

Error in ode45 (line 114)
[neq, tspan, ntspan, next, t0,
tfinal, tdir, y0, f0, odeArgs,
odeFcn, ...

So, I tried changing my initial conditions from [2,7,5] to [2,7,5,8,9,4]. When I did this, I got the same message, but instead of saying that the vector returned is length 6, and that the length of my initial condition vector was 3, it said that the vector returned was of length 12, and that the length of my initial condition vector was 6.

Why is it doing this? This seems strange that the length of the vector returned would vary as I vary the length of the initial condition vector.

Was it helpful?

Solution

Have you looked at the contents of DE_19.m? You should provide the code you used before calling matlabFunction, but here's a runnable version that might be something like what you used:

syms a16 x16;
DE_19 = matlabFunction([a16;-((1+x16^2)/(2*x16))*a16],'vars',{x16,[a16]})

This returns:

DE_19 = 

    @(x16,a16)[a16;(a16.*(x16.^2+1.0).*(-1.0./2.0))./x16]

As you can see, if you pass in a scalar state (the second argument, a16, is the state and the first, x16 is the independent variable – this is true for all ODE solvers: t then y), the output will always two elements. And indeed the output will always be twice as long as the input state. Maybe a16 and x16 should be switched? Look at the help and documentation for matlabFunction as they provide an example that does exactly this.

By the way, there's no real need to create a file. You can use the anonymous function returned by matlabFunction like this (you'll need to figure out which variable is which and what is missing to still get it to work):

DE_19 = matlabFunction([...],'vars',{...})
[x,y] = ode45(DE_19,[1,11],[2,7,5]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top