# putting a trendline on a semi-log plot in MatLab.

21 views (last 30 days)
Shinichiro Shimata on 3 Mar 2021
The values are as following,
avgspeed = [27.7846701084929; 31.1385896602218; 33.3643634350556; 37.0654321948195; 38.5042712877777; 41.3807720015859] ;
height = [13; 33; 55; 155; 245; 519];
semilogy(avgspeed, height)
How do I code to find the equation of trendline for this semi-log plot?

William Rose on 4 Mar 2021
To add the trendline quation to the plot, see last two lines of the code below.
avgspeed = [27.78; 31.14; 33.36; 37.07; 38.50; 41.38]; %the x values
height = [13; 33; 55; 155; 245; 519]; %the raw y values
%next: make a matrix with a column of ones and a column of the x values
X=[ones(length(avgspeed),1) avgspeed]; %X=(column of ones,column of x values)
Y=log10(height); %log(height), for the regression
%next line: the standard matrix equation for a linear regression
b=inv(X'*X)*X'*Y; %b(1)=intercept, b(2)=slope
predheight=10.^(X*b); %the heights predicted by the linear regresison
semilogy(avgspeed,height,'rx',avgspeed,predheight,'r-');
xlabel('Avg.Speed'); ylabel('Height');
textstr=sprintf('Pred.Height=\n10^{(%.3f+%.3f*AvgSpeed)}',b(1),b(2));
text(27,520,textstr);
The code above produces the plot below. William Rose on 3 Mar 2021
Edited: William Rose on 3 Mar 2021
Here is the solution. Your question demonstrates Matlab's power and code efficiency: it takes only 6 lines of code, after the data is specified, and no toolbox functions are needed. Most of the text below is just comments.
avgspeed = [27.78; 31.14; 33.36; 37.07; 38.50; 41.38]; %the x values
height = [13; 33; 55; 155; 245; 519]; %the raw y values
%next: make a matrix with a column of ones and a column of the x values
X=[ones(length(avgspeed),1) avgspeed]; %X=(column of ones,column of x values)
Y=log10(height); %log(height), for the regression
%next line: the standard matrix equation for a linear regression
b=inv(X'*X)*X'*Y; %b(1)=intercept, b(2)=slope
predheight=10.^(X*b); %the heights predicted by the linear regresison
semilogy(avgspeed,height,'rx',avgspeed,predheight,'r-');
xlabel('Avg.Speed'); ylabel('Height');
And the output is below: If you need to report the equation for the predicted height, it is:
predheight=10^(b1 + b2*avgspeed)
where b=[b1;b2] is calculated in the code.
Shinichiro Shimata on 3 Mar 2021
Thank you so much!
I am still having a hard time displaying equation of the trendline. Could you help me further?
Thanks,

Shinichiro Shimata on 4 Mar 2021
Man, thank you again!!