MATLAB: Removing zeros from a m x n x p matrix.

matrix manipulation

I have a matrix, let's call it "A", that is 6 x 3 x 5 x 5. In my code, I separate each "block" of the matrix so that I now have five 6 x 3 x 5 matrix, A1, A2, A3, A4, A5.
Now in A4, A4(:,:,4) and A4(:,:,5) are both all zeros. How would I remove these from the matrix, leaving A4 as a 6 x 3 x 3 matrix, with non-zero values only? I've tried to use all() but I get an error: "Index exceeds matrix dimensions".
For example if B is m by n, I could use
B(all(B==0,2),:) = [] to remove zero rows. Similarly, I'd like to remove the elements along the all A(:,:,p) that are zero
I'd like to have a way to remove the zero matrices even if I don't know which ones are zeros. For instance it could be any one of the value of "p" for A4(:,:,p). (If I run the program once, it could be 1 5 3, and another time it could be 2 and 4, so merely specifying the rows by hand won't work for more than one run.)

Best Answer

A=rand(6,3,5,5)
for k=1:size(A,4)
B{k}=A(:,:,:,k)
end
A4=B{4}
A4(:,:,4:5)=[]