How to create a function with an algebraic input
10 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I am currently trying to create a function of the form
g(f,x0,epsilon)
where f is an algebraic expression in terms of some symbols x. Specifically, I am using this in a function that takes in an arbitrary function f and approximates a solution to the equation f(x)= x within accuracy epsilon (if possible in sufficiently few steps), starting point x0.
Since f is arbitrary, I am required to define it in my code before i can compute f(x) for an arbitrary numerical input. I attempted this by the following: First I create a function called f:
function [f] = f( y )
f = @(x)(y);
end
Then my function g is of the form
g(y, x0 , epsilon)
Where y is an algebraic expression in x. But this fails as when entering any algebraic expression it comes up with 'Undefined function or variable 'x'.'.
Any help is appreciated.
2 commentaires
James Tursa
le 22 Sep 2017
To be clear, the "y" above in your "f" function is a symbolic expression in terms of the symbol "x"? And you want to solve f(x)=x numerically to within some tolerance?
Réponses (2)
JESUS DAVID ARIZA ROYETH
le 22 Sep 2017
you can do like this:
function f=g(y, x0 , epsilon)
y=str2func(['@(x) ' y]);
%your code
but your input "y" need single quotation marks ( ' ) around them. for example : g('x+1',4,0.01)
0 commentaires
James Tursa
le 22 Sep 2017
Modifié(e) : James Tursa
le 22 Sep 2017
Not really sure what you need, but here are a couple of examples:
Solving with symbolic expression:
>> syms x
>> f = cos(x)
f =
cos(x)
>> S = solve(f-x)
S =
0.73908513321516064165531208767387
>> subs(f,S)
ans =
0.73908513321516064165531208767387
Creating a function handle that you can use with your own numeric solver:
>> fhandle = matlabFunction(f-x)
fhandle =
@(x)-x+cos(x)
0 commentaires
Voir également
Catégories
En savoir plus sur Symbolic Math Toolbox dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!