You can simply just use a pair of for
loops and have the two access variables access the right slice you want1:
for ii = 1 : size(fourDMatrix, 3)
for jj = 1 : size(fourDMatrix, 4)
slice = fourDMatrix(:, :, ii, jj);
% Do your processing here...
end
end
However, if I can recommend using reshape
, you should use it. You can use reshape
to create a 3D matrix where each slice of this is a 2D slice from your 4D matrix, and you simply do:
slices = reshape(fourDMatrix, size(fourDMatrix, 1), size(fourDMatrix,2), []);
This will create a 3D matrix where the rows and columns are equal to those from your 4D matrix. However, the []
at the end of the code will automatically unroll your 4D matrix so that it happens along the third dimension first, followed by the fourth dimension after. It basically determines how many 2D slices in the 3D matrix there are and this will be calculated automatically. For example, if your 4D matrix was called A
and had size 9 x 9 x 4 x 4
, the above code will create a 9 x 9 x 16
matrix where slices(:,:,1)
corresponds to A(:,:,1,1)
, slices(:,:,2)
corresponds to A(:,:,2,1);
and slices(:,:,6)
corresponds to A(:,:,2,2)
. In general, slices(:,:,kk)
would access the slice at A(:,:,floor(kk/size(A,2)) + 1, mod(kk,size(A,2)) + 1
.
1: Variable names cannot start with a number in MATLAB. I've renamed your variable to fourDMatrix
.