 function [T,pvalue,df,S,SE]=test2slopes(X1,A,X2,B,plot)
%  Format [T,pvalue,df,S,SE]=test2slopes(X1,A,X2,B,plot)
% Testing the equality of two slopes
% Using Larsen & Marx Theorem 11.3.9
% Larsen & Marx (2006) Introduction to Mathematical Statistics, 4th edition
% Input X1 & X2 Explanatory variables, no leading 1's, single column
%       A & B  Two response variables
%       plot=1 Scatterplot of data
% Output T=Student's t
%        pvalue= 2-tailed p value;
%        S=variance
%        df=degrees of freedom
%        Standard error for the difference in slopes
% Written by Eugene.Gallagher@umb.edu 11/27/10
[rA,cA]=size(X1);
[rB,cB]=size(X2);
if nargin>4 & plot==1
    scatter(X1,A,'b','*')
    hold on
    plot(X2,B,'mo')
    lsline
    figure(gcf)
    hold off
end
x1=[ones(rA,1) X1];
x2=[ones(rB,1) X2];
BA=regress(A,x1);
BB=regress(B,x2);
YestA=x1*BA;YestB=x2*BB;
ResidA=A-YestA;ResidB=B-YestB;
df=rA+rB-4;
S=sqrt((sum(ResidA.^2)+sum(ResidB.^2))/df);
Xdev2A=sum((X1-mean(X1)).^2);Xdev2B=sum((X2-mean(X2)).^2);
SE=S*sqrt(1/Xdev2A + 1/Xdev2B);
T=(BA(2)-BB(2))/(S*sqrt(1/Xdev2A + 1/Xdev2B));
if T<0
    pvalue=2*tcdf(T,df);
else
    pvalue=2*(1-tcdf(T,df));
end    
