In: Physics
The resistance R of a tungsten wire as a function of temperature can be modeled with the equation
R=R0*[1+α(T-T0 )
whereR0 is the resistance corresponding to temperature T0, and α is the temperaturecoefficient of resistance. Determine R0and α such that the equation will best fit the following data (Use linear regression curve fitting). Take T0 = 20°C.
T=[20 100 180 260 340 420 500]
R=[500 676 870 1060 1205 1410 1565]
After enter below codes it gives an error
function [a,Er]=LinReg(x,y)
[rowx,colx]=size(x);
%x=[20 100 180 260 340 420 500];
[rowy,coly]=size(y);
%y=[500 676 870 1060 1205 1410 1565];
m=colx;
n=coly;
if m~=n
error('Size Of x And y Have to be Same');
end
sumx=0;
for i=1:m
sumx=sumx+x(i);
end
%display(sumx);
sumy=0;
for i=1:m
sumy=sumy+y(i);
end
%display(sumy);
sumx_2=0;
for i=1:m
sumx_2=sumx_2+(x(i).^2);
end
%display(sumx_2);
sumxy=0;
for i=1:m
sumxy=sumxy+(x(i).*y(i));
end
%display(sumxy);
a_1=((n.*sumxy)-(sumx.*sumy))/((n.*sumx_2)-((sumx).^2));
a_0=(((sumx_2).*(sumy))-((sumxy).*(sumx)))/((n.*sumx_2)-((sumx).^2));
a(1)=a_1;
a(2)=a_0;
Er=0;
for i=1:m
Er=Er+(((y(i)-(a_1.*x(i)+a_0))).^2);
end
end
%ERROR:
Not enough input arguments.
Error in LinReg1 (line 3)
[rowx,colx]=size(x);
So, if we want to fit a linear regression line,
I am using the following simple linear regression formulae:
for a linear regression model: y = a + b*x,
where, b is slope and a is intercept
matlab code:
%%%%%%%% function LinReg.m %%%%%%
function [R0,alpha,SSE,SST,Rsq] = LinReg(x,y,T0)
n = length(x);
m = length(y);
if n ~= m
disp('x and y are of different lengths, regression will be
inaccurate; proceeding anyhow...\n');
if n > m
n = m;
end
end
x_avg = sum(x(1:n))/n;
y_avg = sum(y(1:n))/n;
num = 0.0; % stands for numerator
denom = 0.0; % stands for denominator
for i = 1:n
num = num + (x(i) - x_avg)*(y(i) - y_avg);
denom = denom + (x(i) - x_avg)^2;
end
slope = num/denom;
intercept = y_avg - slope*x_avg;
R0 = intercept + slope*T0;
alpha = slope/R0;
SSE = 0.0; % sum of squared error
SST = 0.0; % total sum of squares
for i = 1:n
SSE = SSE + (y(i) - intercept - slope*x(i))^2;
SST = SST + (y(i) - y_avg)^2;
end
Rsq = (SST - SSE)/SST;
end
%%%%%%% end of LinReg.m %%%%%%
%%%%%%% main.m %%%%%%
T = [20 100 180 260 340 420 500];
R = [500 676 870 1060 1205 1410 1565];
T0 = 20;
[R0,alpha,SSE,SST,Rsq] = LinReg(T,R,T0);
fprintf('R0 = %f\n',R0);
fprintf('alpha = %f\n',alpha);
fprintf('SSE = %f\n',SSE);
fprintf('SST = %f\n',SST);
fprintf('SSR = %f\n',SST-SSE);
fprintf('Rsq = %f\n',Rsq);
%%%%%%%% end of main.m %%%%%%
screenshots of code:
LinReg.m :
main.m :
output:
We see that Rsq is very close to 1. So the fit is a good fit.
----------------------X------------------------X---------------------X--------------------
If you find this answer helpful, please give it a thumbs up. Thank you.