Search code examples
matlabloopsmatrixmatrix-indexing

Extract several columns from 3d matrix


I currently have an array A which has dimensions N x t x t. I want to create a 2D matrix, N x t, of the form:

B = [ A[:,1,1] A[:,2,2],...,A[:,t,t]]

Obviously, 2 ways I could do this are writing it out in full (impractical since t is large) and loops (potentially slow). Is there a way to do this without loops. I figured it would work if I did:

B = A[:,[1:end],[1:end]]

but that just gave me back the original matrix.


Solution

  • Basically, you need to start thinking about how to reorganize your matrix.

    From

    A = randn([5 3 3]);
    

    Let's look at

    A(:,:)
    

    Basically you want columns 1, 5, 9. Thinking about it, knowing t = 3, from the present column you want to increment by t + 1. The formula is basically:

    ((1:3)-1)*(3+1)+1 %(or (0:2)*(3+1) + 1)
    

    Which plugged in A yields your solution

    A(:,((1:3)-1)*(3+1)+1)
    

    In a general format, you can do:

    A(:,((1:t)-1)*(t+1)+1)
    

    EDIT:

    Amro basically just put me to shame. The idea is still the same, it just becomes more readable thanks to end

    Therefore use:

    A(:,1:t+1:end)