Search code examples
matlabsymbolic-mathminimization

How to make a symbolic function in MATLAB based on user input


I'm trying to make a symbolic function in MATLAB based on parameters input by a user and then minimize that function using fminsearch(fun, x0), which seems to only allow symbolic functions. I can't seem to find a way to generate an arbitrary symbolic function based on user input other than sym2poly(), which only works if I want to generate a polynomial function. Any ideas?


Solution

  • I think that str2func is what you are looking for:

    % this is actually your user input, it could be taken,
    % for example, using inputdlg function
    user_in = inputdlg('Enter your function:','Function'); % '2*x + 4'
    
    % the user input is transformed into a function handle 
    % that can be passed to fminsearch
    fh = str2func(['@(x) ' user_in]);
    
    % the function created from the user input is evaluated 
    x = fminsearch(fh,x0);
    

    You could also let the used define the input arguments (but I don't think this is necessary with fminsearch):

    str = '@(x,y) 2*x + 4*y + 1';
    fh = str2func(str);
    

    For more infos: