0

I've got a huge 4D matrix and I need to slice it into 2D matrices. It's easy to do this manually one by one:

slice1 = 4dmatrix(:,:,1,1)
slice2 = 4dmatrix(:,:,1,2)

etc but I can't work out how to do this using loops. Everything I've seen so far reshapes the original matrix (which I don't want).

rayryeng
  • 102,964
  • 22
  • 184
  • 193
emmetbug
  • 13
  • 1
  • So what exactly do you want? Do you want to create a 3D matrix where each slice is a 2D slice of this 4D matrix? What is the desired output? – rayryeng Oct 20 '16 at 17:18
  • 3
    Just index this way in a loop `D4matrix(:,:,ii,jj)` where you loop over `ii` and `jj`. Don't create all the 2D slices separately, that's called [dynamic variable naming](http://stackoverflow.com/questions/32467029/how-to-put-these-images-together/32467170#32467170) and is considered a bad programming habit. Also: you can't actually name your matrix `4dmatrix`, as variable names can't start with a numeral. – Adriaan Oct 20 '16 at 17:19

1 Answers1

1

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.

rayryeng
  • 102,964
  • 22
  • 184
  • 193
  • 1
    Thanks, I think I'd misunderstood reshape from the documentation, that's exactly what I wanted. – emmetbug Oct 21 '16 at 11:43
  • No problem at all. I'm glad I could help! I've also added in a couple of sentences about `reshape` to avoid confusion. This may help in your further understanding behind how it works. – rayryeng Oct 21 '16 at 14:19