How to dynamically execute code stored in a string variable

10 Ansichten (letzte 30 Tage)
mihai
mihai am 31 Okt. 2014
Bearbeitet: mihai am 1 Nov. 2014
I do a small toolbox to ease ODE simulation. The script until now works well like this:
(example)
ev1 = @(T,Y)ev1(T,Y,a);
options = odeset('Events',ev1,... ...);
But given that the script should read plenty of event functions and make a list for a pop-up so the user could select them easy, I want it to check in a certain folder for all the files that are functions. The user will simply create the files like this:
% eventFile @(T,Y)ev1(T,Y,...other parameters...);
function [value,isterminal,direction+ = .... ....
... ...
end
the program would read the first line of all the files and if it finds eventFile keyword will save the @(T,Y.....; in a string. Can this string be converted or be used to construct an object like this: ev1 = @(T,Y)ev1(T,Y,a); so I can put it in the odeset 'Event' parameter, just like ev1 in the first example?
If you think this could be done in a different way and I should completely change my plans please tell me.
I tried to make this short and clear, but if I wasn't clear enough, tell me and I will try to explain my problem better.
Later edit: the previous title was "How can I convert a strings like "@(T,Y)event(T,Y,a)" in a function object just like ev = @(T,Y)event(T,Y,a);"

Akzeptierte Antwort

per isakson
per isakson am 1 Nov. 2014
Bearbeitet: per isakson am 1 Nov. 2014
"an object like this ev1 = @(T,Y)ev1(T,Y,a); " &nbsp that is an Anonymous Functions
Try
>> ev1 = @(t,y) fprintf('ev1: %d, %d\n', t, y )
>> str = '@(T,Y) ev1(T,Y)';
>> foo = eval( str );
>> foo(1,2)
returns
ev1: 1, 2
  2 Kommentare
mihai
mihai am 1 Nov. 2014
Bearbeitet: mihai am 1 Nov. 2014
Thank you! This eval function is amazing... I didn't expected it to exist.
Now, I know the question I made is not so general.. should I edit it? Any advice for a better title?
per isakson
per isakson am 1 Nov. 2014
Bearbeitet: per isakson am 1 Nov. 2014
I think this is a justifiable use of &nbsp eval. &nbsp However, it should be the used only as a last resort.
Maybe, "How to dynamically execute code stored in a string variable" would be a better title.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Simulink Environment Customization finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by