General function in symbolic toolbox

11 次查看(过去 30 天)
Is it possible in the matlab symbolic toolbox to define general functions, i.e. to define functions only as a general mapping from agruments to output without defining the functional form?
E.g. I would like to define f(x). Then id like to use f(x) in a number of symbolic operations. E.g.
syms x y;
%define general function
Equation=f(x)+y;
Grad=gradient(Equation,[x, y])
Now for grad id like to get Grad = [ derivative(f(x),x) , y ]
Then id be able to youse matlabFunction to create a matlab function from that, replacing all references to f(x) by the relevant functional form.
(I could of course assume this functional form from the beginning but then id have to rerun the code for every change in f(x) and in my application it would also be too slow since matlab would subsitute out f(x) everytime its used.)

采纳的回答

Star Strider
Star Strider 2014-5-20
编辑:Star Strider 2014-5-20
Beginning with R2012a, it has been possible to define functions in the Symbolic Math Toolbox the way you would normally define functions:
syms t x y
f(x) = x^2 + 2*x + 1
g(t) = 10*exp(-t)
h(x,t) = x^2 - t^2
r1 = f(pi)
r2 = g(5)
r3 = h(3,5)
gradh = gradient(h)
grh = matlabFunction(gradh)
All give the expected numeric and symbolic results.

更多回答(2 个)

dominik
dominik 2014-5-20
Hi Thanks for the answer, it seems I havent expressed my question clearly.
In what you propose you define the function explicitly. E.g. f(x) = x^2; Then derivative(f(x)) evaluates to 2*x; This is exactly what i do NOT want to do. Since the function and the operations with the functions are so complex that it makes matlab infeasibly slow.
I want to keep the function as a placeholder only. As if it was a constant, only when deriving treat it as a general function of its arguments (and apply the chain rule). something like f(x)=f(x); Then derivative(f(x),x) evaluates to d_f(x); where f(x) and d_f(x) are unknown functions, all we know is the latter is the derivative of the former
  17 个评论
Leo Simon
Leo Simon 2016-5-3
Hi Dominik. Were you ever able to get a resolution of this issue? I have the same one. Thanks! leo

请先登录,再进行评论。


Martin Ahrnbom
Martin Ahrnbom 2020-6-16
I know this is an old question, but I was looking for this too and it took me a while to figure it out. The proper solution is the following:
syms x f(x)
Then you can do stuff like
fp = diff(f, x); % Compute derivative
And if you do end up creating an actual function later, like
F = x.^2 + 3;
then you can use the 'subs' function to substitute your general function with a specific one, like
subs(fp, f, F) % outputs 2*x

类别

Help CenterFile Exchange 中查找有关 Calculus 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by