# How to fit a log curve to a scatterplot?

126 views (last 30 days)

Show older comments

Could anyone advise me on how to a fit a curve to this plot?

The y-axis is decibels and so logarithmic.

I have tried the help page of lsqcurvefit but clearly using the wrong inputs as the curve doesn't align with the points.

x=slopeDist; %18 distances in km

y=PSD; %18 dB values from 50-90

scatter(x,y)

p = polyfit(x,y,1);

f = polyval(p,x);

plot(x,y,'o',x,f,'-')

legend('data','linear fit')

%fits a line but we want a curve!

%Log curve? Doesn't work...

fun = @(x,xdata)x(1)*exp(x(2)*xdata);

x0 = [100,-1];

x = lsqcurvefit(fun,x0,xdata,ydata)

times = linspace(xdata(1),xdata(end));

plot(xdata,ydata,'ko',times,fun(x,times),'b-')

legend('Data','Fitted exponential')

title('Data and Fitted Curve')

##### 1 Comment

Walter Roberson
on 31 May 2021

### Answers (1)

Star Strider
on 28 May 2021

Edited: Star Strider
on 28 May 2021

##### 6 Comments

Star Strider
on 31 May 2021

This is the best I can do —

LD = load('data.mat');

outsort = sortrows(LD.out); % Not Sorting The Rows Creates Problems For The Regression

x = outsort(:,1);

y = outsort(:,2);

fcn = @(b,x) b(1).*exp(b(2).*x) + b(3);

B = fminsearch(@(b)norm(fcn(b,x)-y), [90; 0.001; 60] );

yfit = fcn(B,x);

expstr = @(x) [x(:).*10.^ceil(-log10(abs(x(:)+(x==0)))) floor(log10(abs(x(:)+(x==0))))];

figure

scatter(x, y)

hold on

plot(x, yfit, '-r')

hold off

grid

text(2.5E+5, 77.5, sprintf('$y = %.1f\\ e^{%.1f\\times 10^{%d} \\ x} +%.1f$',B(1),expstr(B(2)),B(3)), 'Interpreter','latex', 'FontSize',15);

I added the equation for the regression. Remove that if it is not necessary. (The ‘expstr’ function generates the matissa and exponent from ‘B(2)’ here. It looks better than displaying all the leading zeros in the regression equation. If you do not want to display the regression equation, the function is not otherwise necessary for the code.)

.

### See Also

### Categories

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!