Reputation: 473
If I have anonymous function, for example:
a=3;
b=4;
y = @(x) (x)./(a+b+x);
So I easily can find a for x=4, but how can I find an x that will give me y=0.4? I actual looking for an easy way to have x(y) instead of y(x).
Upvotes: 2
Views: 389
Reputation: 2854
One approach is to use MATLAB's interpolation (1D) function interp1
, but this works on your function for parameter values that ensure y(x)
is a non-decreasing function.
step = .01; % Control precision (smaller = more precise)
Xmax = 50; % Largest x of interest
X = [0:step:Xmax]';
Y = y(X); % Generate discrete approximation of function
yinvh=@(L) interp1(Y,X,L);
Targets = [0.25 0.4 0.75]';
yinvh(Targets)
This matches the results from Cris Luengo's approach.
>> yinvh(Targets)'
ans =
2.3333 4.6667 21.0000
figure, hold on, box on
plot(X,y(X))
plot(zeros(3,1),Targets,'rx')
plot(yinvh(Targets),zeros(3,1),'rx')
for k = 1:length(Targets)
plot([0; yinvh(Targets(k))],Targets(k)*ones(2,1),'k--')
plot(yinvh(Targets(k))*ones(2,1),[0 Targets(k)],'k--')
end
Upvotes: 1
Reputation: 60790
One trivial approach is to use a numeric algorithm to find the zero of y(x) - 0.4
:
target = 0.4;
x = fzero(@(x) y(x)-target, 0)
Now, x
is 4.6667
and y(x)
returns 0.4
.
Note that this is an easy approach, but it is not cheap computationally. Also, you need a suitable start point, which here I've set to 0
. If your function has multiple points where it reaches 0.4
, then you will get the one closest to this start point.
Upvotes: 3