MATLAB: Fitting data in x,y to a known function

curve fittingfitfunctionMATLABnonlinear

Hi everyone. I have a function that is f = 1/(a+b*x) where a and b are the values to obtain and I have some data:
x1 = linspace(1,32,32);
y1 = [0.01 0.02 0.02 0.02 0.02 0.02 0.03 0.03 0.03 0.04 0.04 0.05 0.05 0.06 0.07 0.07 0.08 0.10 0.11 0.14 0.14 0.17 0.17 0.16 0.21 0.31 0.31 2.43 2.43 29.53 29.53 29.53];
I need to fit these two variables x1 and y1 into the function above to obtain a and b. How can I do this?
I'm sorry I'm pretty new in Matlab. Thank you.

Best Answer

Use the fminsearch function to fit your data:
x1 = linspace(1,32,32);
y1 = [0.01 0.02 0.02 0.02 0.02 0.02 0.03 0.03 0.03 0.04 0.04 0.05 0.05 0.06 0.07 0.07 0.08 0.10 0.11 0.14 0.14 0.17 0.17 0.16 0.21 0.31 0.31 2.43 2.43 29.53 29.53 29.53];
f = @(p,x) 1./(p(1) + p(2).*x);
P = fminsearch(@(p) norm(y1 - f(p,x1)), rand(2,1));
x1v = linspace(min(x1), max(x1));
figure
plot(x1, y1, 'p')
hold on
plot(x1v, f(P,x1v), '-r')
hold off
grid
producing:
P =
0.845464263829100
-0.025490734971736
where ‘P(1)=a’, and ‘P(2)=b’.
The plot appears correct, even though it looks a bit strange.