]>

The FCNCHK Function

The fcnchk function is a very useful function to know if you have code that you wish to use for many different functions. Define your solution as a function that accepts a string that describes another function or can be used to accept the name of another function. Then, call your solution function and send the function string or the name of the particular function you wish your solution function to use.

For example, let's say we want to write our own function that plots other functions over the range -10 to 10. Our solution must:

  1. Create many x-coordinate values from -10 to 10.
  2. Evaluate the other function at all x values and save as y-coordinates.
  3. Use the plot command to plot x versus y.

Here's a function that attemps to do just that. However, it doesn't quite work. Can you recognize and explain why it doesn't work?

    function result = plot_function( f )
    % Plot the function f(x) from -10 to 10 in increments of 0.1
    x = -10 : 0.1 : 10 ;
    y = f( x ) ;
    plot( x , y )

Actually, the above solution function will work just fine if we first define a function named 'f' that accepts a single input and evaluates the function in which we are interested. But defining a function just to plot it doesn't make much sense if you will not need the function otherwise.

Instead, we use fcnchk function to create a function handle that can then be used by our plot_function function. Revise the above plot_function function as follows:

    function result = plot_function( f_x )
    % Plot the function f(x) from -10 to 10 in increments of 0.1
    % f_x is a string that describes the function f(x)
    f = fcnchk( f_x , 'vectorized' ) 
    x = -10 : 0.1 : 10 ;
    y = f( x ) ;
    plot( x , y )

Try your plot_function by calling it from the command window with any (or all) of the following commands:

    >> plot_function( 'x.^2-2' )

or

    >> plot_function( 'sin' )

or

    >> plot_function( 'cos(x)' )

Notice that the function name can be a string that defines the function. The inclusion of 'vectorized' in the call to fcnchk means that it will replace matrix operators with element-wise (dot) operators in the function string. Do not include the 'vectorized' term if you intend to pass the names of user-defined functions instead of a string of the function's terms.

Use the form [f,msg] = fcnchk(...) if it is necessary to check any error message before using the results of the fcnchk call.

Note: fcnchk is a helper function for fzero and quad so they can compute with string expressions in addition to m-file functions.