Parameterize function without anonymous or nested functions

1 vue (au cours des 30 derniers jours)
dkv
dkv le 17 Mar 2017
I'm looking to parameterize a function for the purpose of passing it to an ODE solver e.g. ode45. I'd like to do this
a=5; b=10;
ydot = @(t,y) myodefn(t,y,a,b)
[t,y] = ode45(ydot, tspan, y0)
where
function ydot = myodefn(t,y,a,b)
ydot = a*y+t*b
However, I'm using this inside of MATLAB Coder and therefore using anonymous functions and nested functions is not an option. Right now I'm hacking around this problem using globals but that's not pretty and I suspect may be causing me performance issues e.g. I have
global a b
a=5; b=10;
[t,y] = ode45(@myodefn_withglobals, tspan, y0)
where
function ydot = myodefn_withglobals(t,y)
global a b
ydot = a*y+t*b
Is there a nicer way to parameterize myodefn other than using globals? Or, is it more likely that my performance issues are coming from elsewhere?

Réponses (1)

Ryan Livingston
Ryan Livingston le 17 Mar 2017
If you're able to upgrade, anonymous function support was added to MATLAB Coder in MATLAB R2016b:
If not, you can use an approach like:
which is similar to yours but uses persistent variables instead of globals.
Using a profiler like VTune, AMD Code Analyst, prof, gprof, or one of the profiling tools in Visual Studio. If you're profiling MEX files, you can pass the -g option to codegen to do a debug build. This will add debug symbols to the MEX file so you have good source information in the profiler. It has the downside of disabling compiler optimization so you'll be profiling code slightly different from your release build.
In MEX, you can also use tic and toc to get rudimentary timing information:
function foo
coder.extrinsic('tic','toc');
...
tic;
expensiveCode(...);
t = toc;
fprintf('Execution time for expensiveCode: %g\n',t);
...
tic;
otherExpensiveCode(...);
t = toc;
fprintf('Execution time for otherExpensiveCode: %g\n',t);

Catégories

En savoir plus sur MATLAB Algorithm Acceleration dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by