Julia for linear regression

The similarity of the Julia programming language to Matlab and its syntax makes it very easy to translate simple Matlab programs into Julia code. The following code shows simulating linear regression parameter and standard error estimation in Julia and Matlab. The superficial similarity of the code is remarkable.

First, here is the Matlab code:

clc; clear;
vY = randn(100, 1);  % outcome variable
mX = randn(100, 4);  % design matrix
iN = size(vY, 1); % sample size
vBeta = (vY\mX)';  % estimated coefficients
vE = vY - mX*vBeta;  % residuals
dSigmaSq = vE'*vE/iN;  % residual variance
mV = dSigmaSq.*(inv(mX'*mX)); % covariance matrix 
vStdErr = diag(mV);  % std. err. 
vT = (sqrt(iN)*vBeta)./vStdErr;  % t-statistics
[vBeta, vStdErr, vT]

and here is the Julia code

vY = randn(100, 1);  # outcome variable
mX = randn(100, 4);  # design matrix
iN = size(vY, 1); # sample size
vBeta = (vY\mX)';  # estimated coefficients
vE = vY - mX*vBeta;  # residuals
dSigmaSq = vE'*vE/iN;  # residual variance
mV = dSigmaSq[1,1].*(inv(mX'*mX));  # covariance matrix; dSigmaSq.* 
vStdErr = diag(mV)  # std. err.
vT = (sqrt(iN).*vBeta)./vStdErr  # t-statistics
println([vBeta'; vStdErr'; vT']')

Note that Matlab knows how to print matrices without a call to the println function. The main difference here is that Julia does not know that a 1×1 matrix is a scalar and issues a matrix multiplication conformability error, whereas Matlab simply switches to elementwise multiplication which is the mathematically justifiable default.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: