arraysmatlabstencils

How can I create a 3D array by stenciling the columns of a 2D array in MATLAB?


Suppose I have a 2D array called A. I want to create a 3D array called B, whose "pages" are select columns of a stencil moving across A, column-by-column. For example, the first page of B might be the 1st, 3rd, and 5th columns of A. Then the second page would be the 2nd, 4th, and 6th columns of A, etc.

Anyone have an efficient way of doing this is MATLAB?

Thanks!


Solution

  • I am guessing you are looking for this -

    %%// Given 2D array
    A = randi(10,4,12)
    
    t1 = reshape(A,size(A,1)*2,[]);
    t2 = reshape(t1',size(A,2)/2,[],2); %%//'
    B = permute(t2,[2 1 3]) %%// Output 3D array
    

    Output -

    A =
    
         5    10     3     5     6     8     4     3     8    10     8     7
        10     8     3     7     6    10     9     2     7     8     8     5
        10     4     7     8     6     4     5     4     1     1     3     7
         7     7     6     6     1    10     5     8     9     4     3     3
    
    
    B(:,:,1) =
    
         5     3     6     4     8     8
        10     3     6     9     7     8
        10     7     6     5     1     3
         7     6     1     5     9     3
    
    
    B(:,:,2) =
    
        10     5     8     3    10     7
         8     7    10     2     8     5
         4     8     4     4     1     7
         7     6    10     8     4     3
    

    Of course, there is an alternative straight-forward approach for this special case -

    B(:,:,1)=A(:,1:2:end);
    B(:,:,2)=A(:,2:2:end);