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

조회 수: 19 (최근 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
Siddhartha Harsha Ommi 2020년 6월 21일
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에서 Functions에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by