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

12 次查看(过去 30 天)
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

采纳的回答

Siddhartha Harsha Ommi
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by