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 myfunctionab 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 myderivatpointfa
syms x
r subsdifffxxa;
end
This is actually fine, except when we call the function we can't do this:
syms x
myderivatpointxxsinx
The above code will return:
Error using symsubsindex line
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 symsubsref line
Rtilde builtinsubsrefLtilde,Idx;
Error in myfunction line
r subsdifffxxa;
Why not? The reason is that xxsinx is interpreted as an expression, not a function, and so when we attempt to do fx 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 xxsinx
This will yield the correct:
ans
cos
However if we've predefined 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
fx xxsinx;
myderivatpointf
Yielding:
ans
cos
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
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
