MATLAB: Size of subsets of multi-dimensional arrays

MATLABmulti-dimensional array

I have a 3D array like this:
A = rand(2,2,2);
I want to multiply its sub-arrays like this:
A(1,:,:)*A(:,1,:)
But I can't because they are not the same size. This jars with my intuition from linear algebra, since if I restrict one dimension of a 3-D array, I should get a 2-D array (in this case A(1,:,:) and A(:,1,:) should both be 2×2 matrices, and therefore they should commute). It seems MATLAB does not treat all dimensions equal, and only A(:,:,1) is a 2-D array and a 2×2 matrix:
size(A(1,:,:))
size(A(:,1,:))
size(A(:,:,1))
What is the logic of how MATLAB deals with this? Any suggestions for doing operations of this kind?

Best Answer

  • The logic might be easier to see in a larger example
    A=rand(5,5,5);
    I=1:2; J=3:5; K=1:4;
    [p,q,r]=size(A(I,J,K))
    p =
    2
    q =
    3
    r =
    4
    This should make sense because the dimensions p,q,and r correspond to the lengths of the index vectors I,J, and K respectively.
    With expressions like A(1,:,:), which is equivalent here to A(1,1:5,1:5), the same rule applies
    >> [p,q,r]=size(A(1,:,:))
    p =
    1
    q =
    5
    r =
    5
    If you want to take sections of a higher dimensional array and re-organize them as matrices, you can use squeeze or reshape, e.g.,
    squeeze(A(1,:,:))*squeeze(A(:,1,:))