Borrar filtros
Borrar filtros

Dimension mismatch in defining a function for use in ode45

2 visualizaciones (últimos 30 días)
Hi,
I'm solving a system of ODEs with ode45. I would like to have extra (non integrated) parameters out of the function as in here
However for my problem I need to pass in more information too. If I have:
function [dydx k] = myodesimple(x, y, flag, c)
k = x.^2 + y.^2;
dydx = x + k.*y + c;
I can solve using [x,y]=ode45('myodesimple',[0 0.5 1],[0.3]). Then I can use [dydx k]=myodesimple(x,y) to recover k for any x time steps and y solutions.
If I change the function to take in another scalar parameter, say c. I can still recover k after solving with using [x,y]=ode45('myodesimple',[0 0.5 1],[0.3],flag,0.08) by using [dydx k]=myodesimple(x,y,flag,c). The problem comes when trying to solve two equations in the function. If I introduce another eqn:
function [dydx k] = myodecomplex(x, y, flag, c)
k(1) = x.^2 + y(1).^2;
dydx(1) = x + k.*y(1) + c;
dydx(2) = x + (4.*c).*y(2);
k=k(1);
dydx=dydx';
Then ode45 will run with [x1,y1]=ode45('myodecomplex',[0 0.5 1],[0.3 0.2],[],0.08), so I can obtain solutions. However I can no longer obtain k (which should be a column vector). There seems to be something wrong with the dimensions of the vectors I am using but I cannot work out where! The error I get when trying [dydx k]=myodecomplex(x1,y1,flag,0.08) is
"??? In an assignment A(I) = B, the number of elements in B and I must be the same.
Error in ==> myodecomplex at 2
k(1) = x.^2 + y(1).^2;
Any ideas on how I can obtain k, having gained solutions?

Respuesta aceptada

Jan
Jan el 19 de Ag. de 2012
Editada: Jan el 19 de Ag. de 2012
In your code x is a vector, such that:
x.^2 + y(1).^2;
is a vector also. Therefore it cannot be assigned to the scalar k(1). The expression k(1)' is meaningless, because k(1) is a scalar, which is not affected by a transposition. I guess, that you want k instead of k(1).
To pass parameters to the function, use anonymous functions as explained here: Answers: benefit of anonymous functions when using ODE45.

Más respuestas (0)

Categorías

Más información sobre Ordinary Differential Equations en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by