MATLAB: Trouble using eval in a script containing ode45

evalMATLABode45roots

I'm using ode45 to solve a set of equations of motion, but the function file containing said equations also extracts a value from the solution to a polynomial function. More specifically, the function file contains the lines:
syms u %this has to be done to solve for lambda, later
phi=r(1)^2/(1+u)+r(2)^2/(beta^2+u)+r(3)^2/(gamma^2+u)-1; %phi is used to solve for parameter lambda
%solving for parameter lambda
prelim=eval(solve(phi));
sol=find(imag(prelim)<1e-06 & real(prelim)>0); %there should only be one solution that's both real and positive
lambda=real(prelim(sol));
This code segment works as-intended in the Command Window, but always produces the following errors when running a script containing ode45:
Error using ==> evalin
Undefined function or variable 'I'.
Error in ==> sym.eval at 14
s = evalin('caller',vectorize(map2mat(char(x))));
Error in ==> Vesta at 32
prelim=eval(solve(phi));
Error in ==> ode45 at 324
f(:,2) = feval(odeFcn,t+hA(1),y+f*hB(:,1),odeArgs{:});
Error in ==> asteroid_basic at 21
[tau,pth,tau_event,pth_event,index_event]=ode45(@Vesta,tspan,ics,opts);
As I understand it, my problem stems from the use of eval in my function file, since eval tends to change parameters for evalin and assignin–both used by ode45. My question, then: is there a way to effectively use eval in a function file used by ode45, or a simple way to solve an inverse polynomial without using eval?

Best Answer

Do not use eval(solve(phi)) . Instead, use double(solve(phi))
The undefined "I" is the imaginary constant, sqrt(-1), in the symbolic toolbox. MATLAB knows that as "i".
Related Question