Execution time of functions used in anonymous function creation
3 次查看(过去 30 天)
显示 更早的评论
Hello,
What is the best way to force immediate execution of a function that is being used as part of an anoymous function? Do you have to evaluate it in a previous line or can you somehow evaluate it at the same time as defining ?
Here's a simple example:
rng(0)
randomNum = @() rand
defines a very different function than
rng(0)
currentRandom = rand
randomNum = @() currentRandom
Is there a way to get the behavior of the second example with only two lines?
Or here's another more meaningful example:
% Capture current stack
currentStack = dbstack
stackAnalyzer = @(x) stackAnalysisFunction(x,currentStack)
defines a very different function than the much cleaner looking:
% Capture current stack
stackAnalyzer = @(x) stackAnalysisFunction(x,dbstack)
0 个评论
采纳的回答
Walter Roberson
2020-10-26
编辑:Walter Roberson
2020-10-26
What is the best way to force immediate execution of a function that is being used as part of an anoymous function?
stackAnalyer = str2func([@(x) stackAnalyzerFunction(x', struct2str(dbstack), ')'])
where struct2str() is a function that you would have to write that accepts an input struct and outputs a character vector that, when evaluated, builds a struct that had the same contents as the input struct
Thus stackAnalyzer would end up being something like
@(x) stackAnalyzerFunction(x, struct('file', {'/Users/roberson/MATLAB/626/626588/example_fun.m', '/Users/roberson/MATLAB/626/626588/driver.m'}, 'name', {'example_fun', 'driver'}, 'line', {3, 17}))
However, as there are some data structures that cannot be built from static text, in practice what you would have to end up doing instead is having struct2str() be a call to a serialization routine and the generated result would look something like
@(x) stackAnalyzerFunction(x, deserialize('1gSviPKojg1FuITTmVjoYBIgvfDDowCaw-E40IO3PFwEoyO2cJS05a56UVzWcnDp4.AZj.kfzkQGx0Pd-FAkISK8..auXZiGYi0REiXfBc1KnJiGsIJscBt7bPwMEJRle2-OCU9.NPu.7jaQeiCAgeDU37K8mlL74rDanIezyMn5z05-SnzPsAO'))
In view of the alternatives, are you sure this is wise?
To state things more explicitly:
NO, there is no way to have anything similar to @ evaluate an expression at the time the anonymous function is being built, and store the result in a variable attached to the anonymous function, and refer to the variable in the generated anonymous function.
.. Well, I wouldn't rule it out completely, but it is notoriously hard to inject values into an anonymous function. You can use functions() and access the workspace field and {1} that... but storing values into there is tricky.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!