function [beta,r2,Yt]=stepwise_regression(X,Y,Xt)
% function [beta,r2,Yt]=stepwise_regression(X,Y,Xt)
% This is a convenient interface to Matlab's stepwisefit function
%
% Inputs: 
%
% X     - input data
% Y     - output data
% Xt    - test data (can be empty)
%
% Outputs:
%
% beta    - regression coefficients (with constant offset)
% r2      - coefficient of determination
% Yt      - prediction for Xt
%
[n,d]=size(X);

[beta,se,pval,inmodel,stats]=stepwisefit(X,Y,'display','off');

beta = beta.*inmodel';
beta = [beta;stats.intercept];
Yp = [X ones(n,1)]*beta;
res = Y-Yp;
varY = var(Y,1);
r2   = (varY-mean(res.^2))/varY;

if nargin > 2,
  Yt = [Xt ones(length(Xt(:,1)),1)]*beta;
end 
