Simone Cairone
Simone Cairone

Reputation: 13

Double for loop MATLAB

I need to do an estimation procedure for n time series (n vectors of T observations). I have the formula to evaluate my variable (using a for loop) but I need to repeat this n times (the number of vectors).

h0 = var(residuals);
ht=zeros(T,n); ht(T,1)=h0;
for i=2:T
    ht(i) = theta(1) + theta(2)*residuals(i-1)^2 + theta(3)*ht(i-1);
end          

So this loop calculates ht for all of the observations in series one, but I need another for loop that helps me to use this formula for all of the series.


Edit: This is what I've done based on the below answer:

function ht = VarEQ(theta,residuals)    
    [T,n] = size(residuals)
    for k=1:n
        h0 = var(residuals(:,k));
        ht=zeros(T,n); ht(1,k)=h0;    
        for i=2:T
            ht(i,k) = theta(1,k) + theta(2,k)*residuals(i-1,k)^2 + theta(3,k)*ht(i-1,k); 
        end  
    end
end

Current problem: Now ht is all columns of zero and just the last column of correct values.


Variables

var is a 1xn row vector of variances. Using k, I want just the scalar for each residual.

theta is a 3xn matrix of parameters.

residuals is a Txn matrix.

Upvotes: 1

Views: 119

Answers (1)

Wolfie
Wolfie

Reputation: 30047

This seems simple given what you already have set up:

function ht = VarEQ(theta,residuals)    
    [T,n] = size(residuals)
    ht=zeros(T,n);  % Initialise matrix OUTSIDE loop so it isn't over-written! 
    for k=1:n       % additional loop for series 1 to n
        ht(1,k) = var(residuals(:,k));;    
        for i = 2:T
            % Ensure you are referencing the kth series
            ht(i,k) = theta(1,k) + theta(2,k)*residuals(i-1,k)^2 + theta(3,k)*ht(i-1,k); 
        end  
    end
end

Note: previously, all columns of ht were the same, because theta and residuals were the same for each series!

With your updated code, and the updated code in this answer, that has been fixed.

Upvotes: 1

Related Questions