Defining symbolic derivative inside a nested function and passing the handle to command window or script

15 views (last 30 days)
Hi All, I am a debutant in MATLAB. I am trying to define a symbolic derivative inside a nested function and then pass its handle to command window by calling the parent function. However, when I evaluate the nested function at a certain value from the command window, I get an error as shown further below.
function [f,f_d] = setFunctions_trial
f = @func;
function y = func(x)
y = x^2;
end
f_d = @func_deriv;
function y = func_deriv(x)
syms g(s)
g(s) = f(s);
df = diff(g,s);
y = df(x);
end
end
>> clear all
>> [f,f_d] = setFunctions_trial;
>> f(2)
ans =
4
>> f_d(2)
Error using assignin
Attempt to add "s" to a static workspace.
See Variables in Nested and Anonymous Functions.
Error in syms (line 312)
assignin('caller', y, ysym);
Error in setFunctions_trial/func_deriv (line 9)
syms g(s)
For my purpose I only need symbolic derivative of the func(x) being available in command window or in another script. It need not be inside a nested function. Any other suggestions are welcome.
Thankyou,
Sid

Accepted Answer

Siddhartha Harsha Ommi
Siddhartha Harsha Ommi on 21 Jun 2020
The following code works neatly.
function [f,f_d] = setFunctions_trial
f = @func;
function y = func(x)
y = x^2;
end
f_d = @func_deriv;
function y = func_deriv(x)
s = sym('s');
g = symfun(f(s),s);
df = diff(g,s);
y = df(x);
end
end
>> clear all
>> [f,f_d] = setFunctions_trial;
>> f_d(2)
ans =
4
Sid

More Answers (0)

Categories

Find more on Functions in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!