1

How is it possible to reduce the number of parameters in an anonymous function in MATLAB? Here is an short example:

f = @(p,x) p(1).*x.^2 + p(2);
p = [1,2];
g = @(x) f(p,x);

So long this works fine. But I would like to export the final function with all parameters to a string.

string = func2str(g);

The result is @(x) f(p,x) but in my mind it should be something like @(x) 1.*x.^2 + 2.

How is it possible to realize this?

asked Dec 3, 2013 at 10:34

1 Answer 1

2

You may use the symbolic math toolbox to simplify:

function h = cleanhandle(f)
 syms x;
 h = matlabFunction(f(x));
end

Usage:

>> g2 = cleanhandle(g)
g2 = 
 @(x)x.^2+2.0

Here a version for functions with more than one input argument:

function f=cleanhandle(f)
 n=nargin(f);
 A=sym('A', [n 1]);
 A=mat2cell(A,ones(n,1));
 f=matlabFunction(f(A{:}));
end
answered Dec 3, 2013 at 11:34
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.