Problem

Write a nested function that evaluates a polynomial of the form $y = ax^2+bx+c$. The host function genFunc() should be able to take a varying number of arguments using varargin with a maximum of 3 arguments (a,b,c) to initialize the coefficients of the polynomial. If there is only one argument, then b and c must be set to zero. If there are two input arguments, then c is set to zero. If none are given on input, then the returned function should be zero. If more than 3 arguments exist, then the function should display an error and stop. Also, if the input arguments are not real numbers, then the function should return an error and stop.

On output, the host function should create and return a function handle for the nested function evalFunc(). The nested function should calculate a value of $y$ for a given value of $x$, using the values of $a$, $b$, and $c$ stored in the host function. This is called a function generator since the host function generates and outputs another function that can be called and used later on in the program. Once you create your function generator, test it in the following way: Call genFunc(1,2,0) and save the output function handle in a variable, say h1. Call genFunc(1,2) and save the output function handle in a variable, say h2. Then these two function handles should give the same result, given the same input x values.

Solution

MATLAB

Here is an example implementation of genFunc.m.

Comments