Search code examples
matlabmultidimensional-arrayindexingcell-array

Cells of different sizes - Overcoming exceed index error


I want to find the r^2 for each of the 3rd dimensions (the 3rd dimension is basically columns of data). However, in trying to index into each of the cells with a for loop (to loop through the states and then loop through the sets of data), I run into exceed index issues since some of the third dimensions are small, while others are larger.

I tried to sort the cells first:

[dummy, Index] = sort(cellfun('size', data_O3_spring, 3), 'descend');
S = data_O3_spring(Index);

And then loop through and find the corrcoef (using the data set data_O3_spring, which is in the same form as described above):

for k = 1:7 % Number of states
    for j = 1:17 % largest number of sites
        r2_spring{k}(:,:,j) = power((corrcoef(S{k}(:,:,j), data_PM25_spring{k}(:,:,j), 'rows', 'pairwise')), 2);
    end
end

However, this gives me an exceed index error when I go above 5 (the size of the smallest set of data.

About the format of my data: data_O3_spring is a <1x7> cell containing data for 7 states for the months in spring.

data_O3_spring{1} (one of the states) has 7 cells (different sets of data I'm looking at), each of which is size:

<61x1x7 double>
<61x1x17 double>
<61x1x8 double>
<61x1x16 double>
<61x1x5 double>
<61x1x12 double>
<61x1x13 double>

61 is the number of days (rows). There's 1 column. And the third dimension size is the number of sets of data I'm looking at in that particular state (so it varies by state).

I tried using a while loop, but didn't manage to get it to work either.


Solution

  • I may be missing a detail, but it seems you can change your loop from:

    for j=1:17,
    

    to

    for j = 1:size(S{k},3),
    

    Each state has a different number of sites, and that's fine because you are storing the output in a cell array (r2_spring{k}(:,:,j)), which does not require that the dimension indexed by j be equal.

    Also, pairing corrcoef(S{k}(:,:,j) with data_O3_spring{k}(:,:,j) is a problem since you've reordered data_O3_spring into S. I'd say to try either:

    corrcoef(S{k}(:,:,j), S{k}(:,:,j), 'rows', 'pairwise')
    

    or

    corrcoef(data_O3_spring{k}(:,:,j), data_O3_spring{k}(:,:,j), 'rows', 'pairwise')