MATLAB: Predict y values from x values

polyval

If x=[0 1 2 3 4 5]; and y=[0 20 60 68 77 110]; To get a linear equation I can use coefficients=polyfit(x,y,1) which gives me coefficients 20.8286 3.7619 so my linear equation is y = 20.8286 x + 3.7619 If I want to find an unknown y value from a known x value e.g. 1.5 I can use y=polyval(coefficients, 1.5) and I get y = 35.0048. In other words, using polyval, and using the equation derived from polyfit, when x = 1.5, y = 35.0048.
However, if I want to find an unknown x value from a known y value, what do I do?
Kind regards, Wendy

Best Answer

Hi,
many options to do this - here you have 3 of them. All options start with your known code and want to know the x-value for y = 35.0048:
x=[0 1 2 3 4 5];
y=[0 20 60 68 77 110];
coeffs = polyfit(x,y,1);
y_val = 35.0048;
#1 - Using the elementary Matlab function roots
coeffs_new = coeffs;
coeffs_new(2) = coeffs_new(2) - y_val;
result1 = roots(coeffs_new);
leads to:
result1 =
1.5000
#2 - If you have Symbolic Math Toolbox you can use the finverse function:
syms f(x) f(y)
f(x) = coeffs(1) * x + coeffs(2)
f(y) = finverse(f)
which gives:
f(x) =
(729*x)/35 + 79/21
f(y) =
(35*x)/729 - 395/2187
To calculate values with this you will need a function handle:
f_y = matlabFunction(f(y))
which is:
f_y =
function_handle with value:
@(x)x.*(3.5e1./7.29e2)-1.80612711476909e-1
Then you can calculate the x-value belonging to 35.0048:
>> result2 = f_y(y_val)
result2 =
1.5000
*#3 - Use fsolve* (from Optimization Toolbox) to solve the problem:
result3 = fsolve(@(x)coeffs(1)*x+coeffs(2)-y_val,0)
which results in:
Equation solved.
fsolve completed because the vector of function values is near zero
as measured by the default value of the function tolerance, and
the problem appears regular as measured by the gradient.
<stopping criteria details>
result3 =
1.5000
Best regards
Stephan