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?

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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