In MATLAB, parameters to a function are always evaluated before being passsed to the function. There is no way in MATLAB to be able to define a function with a parameter marked as "hold for later evaluation".
Therefore if you want the user to be able to call
newton_recur(x^2,2*x,1,10)
then x^2 and 2*x must evaluate to something because they will definitely be evaluated before they are passed in to newton_recur
Not only must the x^2 and 2*x evaluate to something but they must evaluate to something useful -- something that directly be evaluated with different values of x, or else something that can be converted to something that can be evaluated with different values of x.
If, before that point, the user had defined x as a numeric value, then x^2 would be those particular numeric values squared, and you would not be able to (reliably) work back from that to a formula to be evaluated for different values.
If, before that point, the user had defined x as a character scalar such as
newton_recur(x^2,2*x,1,10)
then x^2 would be a request to square the internal numeric code used to represent the character vector 'x' -- which happens to be 120. The result would be the same as if the user had coded
newton_recur(x^2,2*x,1,10)
which is not going to do anything useful for you.
What can potentially be used?
- x could be a sym or symfun or symmatrix
- x could be an optimization variable (see optimvar)
- I might have overlooked something
Remember though that for all of these possibilities, x would have had to have been defined as being of the appropriate type before the
newton_recur(x^2,2*x,1,10)
call. If x has not been assigned any value before that call, it is not possible for newton_recur to receive control at all in that statement.
So if you do not have the Symbolic Toolbox or the Optimization Toolbox, what are your choices?
- Use an @(x) introducer to define an anonymous function; Or
- Have the user pass in a character vector or string() scalar, such as newton_recur('x^2', "2*x", 1, 10)
I repeat: in MATLAB it is impossible to define a function that can say "do not evaluate the parameters, just let me see what the user typed there".
(This is not the case for some other symbolic programming languages, such as Maple . In Maple it is possible to define a parameter as being of type uneval to receive what the user typed in for the parameter without having evaluated it as an expression first.)