Averaging subsets of certain dimensions in a 4D matrix in MATLAB
My problem stems from having difficulty conceptualizing 4D matrices (as opposed to 3D). In MATLAB, I have data stored in a 5x5x7x54 matrix. The 5x5 part is symmetric across the diagonal and represents correlations in activity between 5 brain areas. The '7' represents 7 time points and the '54' represents 54 subjects of which there are 17 each in 3 groups (First 17 are Group1, next 17 are Group2, last 17 are Group3).
I would like to average each correlation value across the participant in each group but I want to do this separately for each time point. So for example, I want the average correlation values for the first 17 subjects for timepoint 1, then for timepoint 2, etc. Then I want the average correlation values for the middle 17 subjects for timepoint 1, etc.
In sum, I would have 7 5x5 matrices for each group (so 21 5x5 matrices total).
I am absolute crap at MATLAB so my initial way of thinking about solving this problem was to think of just dividing the matrix up in loops but I know that that will be both confusing and inefficient. Otherwise, though, I'm super lost because I'm having such a hard time conceptualizing the matrix itself.
Can anyone suggest a plan of action?
Ben Voigt's comment is on point, but one can do even a tad better. Since you want to compute the average for each group of subjects, let's separate the subject and group dimensions:
A = reshape(A, [5 5 7 17 3]);
Now you have a five-dimensional array, where the last two dimensions are "subject" and "group". Let's average across subjects:
m = mean(A, 4);
The result is an array with dimension 5 x 5 x 7 x 1 x 3. After averaging, the fourth dimension is a singleton. We can get rid of that:
m = squeeze(m);
After that, the average correlation matrix for timepoint t and group g is m(:, :, t, g).