How to generate function handle automatically from the cell array?
3 次查看(过去 30 天)
显示 更早的评论
I have a 2x1 cell called "dx", which contains 1x3 cells:
'X * k * m' '*' '-1'
'X * k * m' '*' 'Y_XS'
I want this "dx" cell to be converted into a function. How can I do that? The generated function should look like this:
function dX = myFunc(t,X,k,m,Y_XS)
R = X(2) * k * X(1)/(X(1)+m);
dX = [-R;
Y_XS * R];
5 个评论
采纳的回答
Stephen23
2018-4-13
编辑:Stephen23
2018-4-13
@ashadako: you have since edited your question and completely changed the function specification. This answer give the original specification: you can make the required changes yourself.
The trick is to simply arrange the strings as required, and then use str2func to get a function handle:
dx = {...
'X * k * m' '*' '-1'
'X * k * m' '*' 'Y_XS'};
isn = isnan(str2double(dx(:,3)));
tmp = dx;
tmp(:,4) = {';'};
tmp = tmp(:,4:-1:1).';
str = [tmp{:}];
var = sprintf(',%s',dx{isn,3});
str = sprintf('@(t,X,k,m,%s)[%s];',var(2:end),str(2:end));
fun = str2func(str);
This gives an anonymous function, which you can simply call with the required inputs:
>> fun(1,2,3,4,5,6)
ans =
-24
120
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Simulation Setup 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!