Search code examples
matlabstoring-data

Matlab - storing data from a loop in a Matrix (not a vector)


as a part of a bigger script i want to store data from a while loop in a matrix. I want to save parts of the COG_Ton_Av matrix which is 1738x3 in a new matrix. The COG_Ton_Av changes within every loop so i want to store the results outside. I have found multiple entries on how to store the data in a vector, but nothing for a matrix. What i tried is :

valuesforts= zeros(1000,3);
yr =1
while Qn>0 
yindex = Gmhk*100 
zindex = round(gs*100) 
ts = (COG_Ton_Av ((zindex:yindex),:))
valuesforts(yr)=ts
yr = yr+1
end 

I just posted parts of the while loop to make the question easier, I hope it is sufficient to answer the question. While trying this i get following error:

Subscripted assignment dimension mismatch.

Error in cutoff_work14_priceescalation_and_stockpiling (line 286) valuesforts(yr)=ts


Solution

  • The error means that ts is a different size to valuesforts (and it is indexed with yr as a vector.

    If dimensions of TS vary on each iteration of the loop then use cell notation:

    valuesforts = cell(<number of years>);
    ...
    valuesforts{yr} = ts; 
    

    then the dimensions of ts won't matter.

    To extract data also use { } e.g.

    meanValues(yr) = mean(valuesforts{yr});
    

    Bear in mind that the matrix within each cell of valuesforts will have same distentions as ts when it was assigned.

    Alternatively, if TS is always the same size the pre-allocate valuesforts as:

    valuesforts = zeros(<number of years>,<expected length of ts>,3);
    ...
    valuesforts(yr,:,:) = ts;
    

    Then depends on what you want to do with valuesforts.. reshape it or plot it.

    In the worst case (not recommended), you can let the valuesforts grow with every loop iteration. initialise with empty:

    valuesforts=[];
    

    then vertically append ts to valuesforts:

    valuesforts = [valuesforts; ts];
    

    this would give you a matrix with 3 columns and number of years * number of rows in ts in each loop iteration.