Optimizing Recursive Residual Code in Matlab

2 views (last 30 days)
I have coded an algorithm to compute recursive residuals in matlab in a for loop, that is, regressing the second variable on the first, third variable on the first and second, and so on, and calculating the residuals.
While the code works, it's much slower than what I would like (22 seconds second for 200000 observations and 2 variables). I am looking for suggestions to optimize this code, preferably by vectorizing it as much as possible. I am new to Matlab. Please help.
Here is the code that I have been testing:
tic
%Create Random Data
mu = [10, 20];
sigma = [1,1.5;1.5,3];
mu2 = [-10,-20];
RandomData1 = mvnrnd(mu, sigma, 100000);
RandomData2 = mvnrnd(mu2, sigma, 100000);
RandomData3 = [RandomData1;RandomData2];
vargs = [2 0.25 0.5 4];
%Set Variable Size
beta = cell(0);
U = cell(0);
Y = cell(0);
h = zeros(200000,2);
residual = zeros(200000,2);
beta{1} = RandomData3(1,1);
for n=2:200000
for i = 1
residual(n,i) = RandomData3(n,1)-beta{1}/(n-1);
beta{1} = beta{1} + RandomData3(n,1);
h(n,i) = 1/(n-1);
end
for i=2:2
if(i>=n); break; end
% update variance estimate
if(n==i+1) % first time, compute cholesky decomp directly
Xtmp = [ones(n-1,1) RandomData3(1:n-1,1:i-1)];
U{i} = chol(Xtmp'*Xtmp);
Y{i} = Xtmp'*RandomData3(1:n-1,i);
end
x = [1;RandomData3(n,1:i-1)'];
z0 = (U{i}')\x;
z = U{i}\z0;
h(n,i) = x'*z;
w = (U{i}')\Y{i};
beta{i} = U{i}\w;
residual(n,i) = RandomData3(n,i) - x'*beta{i};
% update the cholesky decomp
U{i} = cholupdate(U{i},x);
Y{i} = Y{i} + x*RandomData3(n,i);
end
end
%Calculate Recursive Residuals
h = sqrt(h + 1);
r = bsxfun(@rdivide, residual, h);
toc

Answers (0)

Categories

Find more on Systems of Nonlinear Equations in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!