Search code examples
functionmatlabextract

How to extract numeric parameters from a function handle in MATLAB?


I have a MATLAB function that takes a function handle as an argument, and I need to extract the x and y values from it. The function handle is in the format of @(P) (subs(P, x, <x_value>) == <y_value>).

For example, if the function is called with the argument @(P) (subs(P, x, 2) == 0), I need to extract x = 2 and y = 0. Similarly, if the function is called with the argument @(P) (subs(P, x, 6) == 0), I need to extract x = 6 and y = 0.

How can I achieve this in MATLAB? I'm looking for a way to extract the x and y values from the function handle.

Example inputs:

  • @(P) (subs(P, x, 2) == 0)
  • @(P) (subs(P, x, 6) == 0)

Desired output:

  • For the first input, x = 2 and y = 0
  • For the second input, x = 6 and y = 0

I'm open to using any approach that can help me extract the x and y values from the function handle.


Solution

  • The MATLAB function func2str takes a function handle as input and returns the name or definition of the function. So

    >> fh = @(P) (subs(P, x, 2) == 0);
    >> fText = func2str(fh)
    
    fText =
    
        '@(P)(subs(P,x,2)==0)'
    

    Now you can use MATLAB string parsing functions to get the numbers you want out of that text. There are various ways you could do that and the best one will depend on what possible inputs you need to cope with (could your x and y values be negative? noninteger? expressed in scientific notation?) but for a simple case you could use digitBoundary:

    >> c = split(fText, digitBoundary)
    
    ans =
    
      5×1 cell array
    
        {'@(P)(subs(P,x,'}
        {'2'             }
        {')=='           }
        {'0'             }
        {')'             }
    
    x = str2num(c{2});
    y = str2num(c{4});