In my code, I have a line that looks like this:
f=@(test) bf{i}(5);
where bf is a cell array with functions from str2func() stored in it, i is a variable storing an integer, and the 5 is the argument to pass to the function. How can I get matlab to evaluate the line using the current value of i? Right now when I display f it outputs:
@(test)bf{i}(5)
Lets say i=1, I want it to output:
@(test)bf{1}(5)
Although technically the bf{1} should also be replaced with whatever function is stored in bf{1}. How can I force matlab to evaluate the variables in this statement?
When you create a function handle, the workspace variables are copied and the expression is evaluated when you call the function handle (Typically not a problem in memory consumption, matlab stores only changes).
Now the problem is, to tell Matlab when to evaluate what part of the expression. If you are aiming for a better performance, pre-evaluate all constant parts of the function. Let's say your function is @(x)(g(3).*f(x))
, in this case matlab would evaluate g(3)
on every call.
Instead use:
f=@(x)(x.^2)
g_3=g(3)
h=@(x)(g_3.*f(x))
Now having the constant parts evaluated, you want to see the constants instead of the variabe name. I know two ways to achieve this.
You can use the symbolic toolbox, basically converting the function handle to a symbolic function, then to a function handle again. This not only displays the constants, but also substitutes f
. This is not possible for all functions.
>> matlabFunction(h(sym('x')))
ans =
@(x)x.^2.*4.2e1
Another possibility is to use eval:
h=eval(['@(x)',sprintf('%e',g_3),'.*f(x)'])
Pre-evaluating constant parts of the expressions as I did in the first step is typically recommendable, but both solutions to get the constant visible in your function handle aren't really recommendable. The first solution using matlabFunction
only applies to some functions, while the second comes with all the disadvantages of eval
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments