Question: We've seen now that Matlab Function files can take arguments like myfunction ( a , b ) but what if we want to pass a

We've seen now that Matlab Function files can take arguments like myfunction(a,b) but what if we want to pass a symbolic Matlab function to myfunction? For example what if we want to write a function file which takes a function and a number, takes the derivative of the function and plugs in the number. Can we just do this?
function r = myderivatpoint(f,a)
syms x
r = subs(diff(f(x)),x,a);
end
This is actually fine, except when we call the function we can't do this:
syms x
myderivatpoint(x^2+x+sin(5*x),17)
The above code will return:
Error using sym/subsindex (line 853)
Invalid indexing or function definition. Indexing must follow MATLAB indexing. Function arguments must be symbolic variables, and
function body must be sym expression.
Error in sym/subsref (line 898)
R_tilde = builtin('subsref',L_tilde,Idx);
Error in myfunction (line 3)
r = subs(diff(f(x)),x,a);
Why not? The reason is that x^2+x+sin(5*x) is interpreted as an expression, not a function, and so when we attempt to do f(x) inside of myfunction makes no sense. If we want to pass this expression we must pass it as something called a function handle, so the following will work. The @(x) tells Matlab that what follows is to be interpreted as a function with the variable x, rather than an expression.
syms x
myderivatpoint(@(x) x^2+x+sin(5*x),17)
This will yield the correct:
ans =
5*cos(85)+35
However if we've pre-defined a function ahead of time then we can pass it directly, because Matlab already knows it's a function, so this will work, too:
syms x
f(x)= x^2+x+sin(5*x);
myderivatpoint(f,17)
Yielding:
ans =
5*cos(85)+35
Assignment
Copy the above function code (the first four code lines) into the Function box and change it so it takes two functions f and g and one number a and so it finds the derivative of the composition , plugs in (read that carefully!) and returns that value. Then submit it.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!