How to create a function with an algebraic input

10 visualizzazioni (ultimi 30 giorni)
Evgeny
Evgeny il 22 Set 2017
Modificato: James Tursa il 22 Set 2017
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 Commenti
James Tursa
James Tursa il 22 Set 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?

Accedi per commentare.

Risposte (2)

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH il 22 Set 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)

James Tursa
James Tursa il 22 Set 2017
Modificato: James Tursa il 22 Set 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)

Categorie

Scopri di più su Symbolic Math Toolbox in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by