When does an anonymous function reach a specified value?
8 views (last 30 days)
Show older comments
I get the feeling this a rather simple question, but I cannot seem to get this to work how I want.
Consider an equation, say, y = e^(a*x). I want to find the first x-value where y crosses a threshold, say, y>100. The function is written in MATLAB as an anonymous function, i.e.,
y = @(x) exp(a*x);
How would I go about solving for x? Ideally I want something more specific/robust then simply plotting the function and eyeballing/using the plot tools to estimate the x-value.
0 Comments
Accepted Answer
More Answers (2)
John D'Errico
on 5 Sep 2023
Since you do not provide a value for a, there is no numerical solution possible.
However, as long as the function is a simple one like this, the answer is just as simple. I'll use the symbolic toolbox. We just need to solve for the value of x.
syms x a
ytarget = 100;
yfun = exp(a*x);
xtarget = solve(yfun == ytarget,x)
And that gives us a nice EXACT analytical result. For any value of a, we can know the value of that would achieve the desired target value for y. We can even turn this into a function we can use.
xfun = matlabFunction(xtarget)
For example, when a==0.5, the answer will be...
format long g
xfun(0.5)
Easy enough. Of course, this will not always be the case. Then you might need to resort to numerical methods.
0 Comments
Dyuman Joshi
on 5 Sep 2023
It's not possible to determine the exact value which satisfies the condition you have stated, but you can get an approximate value, by finding the minimum value of the function, which will depend upon the tolerance you define -
%Random value
a=2;
val=100;
%Original function
y1 = @(x) exp(a*x);
%Function to be minimised
y2 = @(x) abs(y1(x)-val);
%Starting point
x0 = 0;
%Set options as required
options = optimset('Display','iter','TolX',1e-10);
x = fminsearch(y2,x0,options)
format long
%x value
x
%Value of the original function at the point
y1(x)
%Value of the function that was minimised at the point
y2(x)
0 Comments
See Also
Categories
Find more on Symbolic Math Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!