How to create a function with an algebraic input
조회 수: 10 (최근 30일)
이전 댓글 표시
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
James Tursa
2017년 9월 22일
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?
답변 (2개)
JESUS DAVID ARIZA ROYETH
2017년 9월 22일
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
James Tursa
2017년 9월 22일
편집: James Tursa
2017년 9월 22일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!