Tony Chivers
Tony Chivers

Reputation: 191

Double for loop in MATLAB, storing the information

I have two for loops in MATLAB.

One of the for loops leads to different variables being inserted into the model, which are 43 and then I have 5 horizons.

So I estimate the model 215 times.

My problem is I want to store this in 215x5 matrix, the reason I have x5 is that I am estimating 5 variables, 4 are fixed and the other one comes from the for loop.

I have tried to do this in two ways,

Firstly, I create a variable called out,

out=zeros(215,5);

The first for loop is,

for i=[1,2,3,4,5];

The second for loop is,

for  ii=18:60;

The 18:60 is how I define my variables using XLS read, e.g. they are inserted into the model as (data:,ii).

I have tried to store the data in two ways, I want to store OLS which contains the five estimates

First,

out(i,:)=OLS;

This method creates a 5 x 5 matrix, with the estimates for one of the (18:60), at each of the horizons.

Second,

out(ii,:)=OLS;

This stores the variables for each of the variables (18:60), at just one horizon.

I want to have a matrix which stores all of the estimates OLS, at each of the horizons, for each of my (18:60).

Minimal example

clear;

for i=[1,2,3,4,5];
    K=i; 
    for  ii=18:60
        x=[1,2,3,i,ii];
        out(i,:)=x;       
    end
end

So the variable out will store 1 2 3 5 60

I want the variable out to store all of the combinations

i.e.

1 2 3 1 1
1 2 3 1 2
  ...
1 2 3 5 60

Thanks

Upvotes: 2

Views: 443

Answers (2)

Cris Luengo
Cris Luengo

Reputation: 60443

The simplest solution is to use a 3D matrix:

for jj=[1,2,3,4,5];
    K=jj;
    for ii=18:60
        x=[1,2,3,jj,ii];
        out(ii-17,jj,:)=x;       
    end
end

If you now reshape the out matrix you get the same result as the first block in etmuse's answer:

out = reshape(out,[],size(out,3));

(Note I replaced i by jj. i and ii are too similar to use both, it leads to confusion. It is better to use different letters for loop indices. Also, i is OK to use, but it also is the built-in imaginary number sqrt(-1). So I prefer to use ii over i.)

Upvotes: 1

etmuse
etmuse

Reputation: 505

As you've discovered, using just one of your loop variables to index the output results in most of the results being overwritten, leaving only the results from the final iteration of the relevant loop.

There are 2 ways to create an indexing variable.

1- You can use an independent variable, initialised before the loops and incremented at the end of the internal loop.

kk=1; 
for i=1:5
    for ii=18:60
        %calculate OLC
        out(kk,:)=OLC;
        kk = kk+1;
    end 
end

2- Use a calculation of i and ii

kk = i + 5*(ii-18)  

(Use in loop as before, without increment)

Upvotes: 0

Related Questions