How can I raise an anonymous expression to a power?
显示 更早的评论
I am trying to replicate the quotient rule for finding derivatives using anonymous functions. I cannot figure out a way to raise one anonymous function to a power for this to work. Here is what I have
syms x
f1 = @(x) (x+1).*(x-3);
g1 = @(x) x.^3 + 2.*x +1;
h = @(x) f1(x)./g1(x);
df1dx = diff(@(x) f1(x), x);
dg1dx = diff(@(x) g1(x), x);
dhdx = diff(@(x) h(x), x);
simplify(dhdx)
% The below line does not work, and I cannt figure out why...
quotient = (f1.*dg1dx - df1dx.*g1) / (g1).^2;
simplify(quotient)
How can I use a power with this function?
1 个评论
Dustin
2014-6-16
编辑:Star Strider
2014-6-16
回答(2 个)
Rashmil Dahanayake
2014-6-9
编辑:Rashmil Dahanayake
2014-6-9
Firstly correct the definition the inline functions for differentiation. Start the command with @ symbol. When calling inline functions you must pass an argument. eg F(x).
Updated code
syms x
f1 = @(x) (x+1).*(x-3);
g1 = @(x) x.^3 + 2.*x +1;
h = @(x) f1(x)./g1(x);
df1dx = @(x) diff(f1(x), x); % note the location of @ symbol
dg1dx =@(x) diff(g1(x), x);
dhdx = @(x) diff(h(x), x);
simplify(dhdx(x)) % pass an argument to the function
quotient = (f1(x).*dg1dx(x) - df1dx(x).*g1(x)) / (g1(x)).^2;
simplify(quotient)
Star Strider
2014-6-9
编辑:Star Strider
2014-6-9
The Symbolic Toolbox will work with anonymous functions, but it prefers not to, because anonymous functions prefer numeric inputs.
‘Undefined function 'power' for input arguments of type 'function_handle'.’
Try this instead:
syms x
f1(x) = (x+1).*(x-3);
g1(x) = x.^3 + 2.*x +1;
h(x) = f1(x)./g1(x);
df1dx = diff(f1(x), x);
dg1dx = diff(g1(x), x);
dhdx = diff(h(x), x);
simplify(dhdx)
% The below line does not work, and I cannt figure out why...
% (It does now!)
quotient = (f1.*dg1dx - df1dx.*g1) / (g1).^2;
quotient = simplify(collect(quotient))
% Compare:
quotient2 = diff(f1/g1, x);
quotient2 = simplify(collect(quotient2))
Not surprisingly, the same answer.
If you want to use anonymous functions outside of the Symbolic Math Toolbox to calculate numeric derivatives, it‘s easy enough:
dfdx = @(f,x) (f(x+1E-8)-f(x)) ./ 1E-8; % Generic derivative function
f = @(x) x.^2; % Function to differentiate
x = 0:5; % Evaluate function & derivative
fx = f(x)
dfx = dfdx(f,x)
produces:
fx =
0.0000e+000 1.0000e+000 4.0000e+000 9.0000e+000 16.0000e+000 25.0000e+000
dfx =
10.0000e-009 2.0000e+000 4.0000e+000 6.0000e+000 8.0000e+000 10.0000e+000
With your functions:
f1 = @(x) (x+1).*(x-3);
g1 = @(x) x.^3 + 2.*x +1;
quotnt = f1(x)./g1(x)
dquotnt1 = (f1(x).*dfdx(g1,x) - dfdx(f1,x).*g1(x)) ./ (g1(x)).^2
dquotnt2 = dfdx(@(x) f1(x)./g1(x),x)
The result produced by dquotnt1 is negative. The dquotnt2 expression gives the correct result.
类别
在 帮助中心 和 File Exchange 中查找有关 Calculus 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!