Doug's MATLAB Video Tutorials

January 10th, 2012

How to do a matrix reshape by ‘blocks’

This week’s video covers a non-standard way of reshaping a matrix. Instead of using the reshape function, this kind of matrix manipulation must be done with for loops. This matrix reshape operation treats submatrices within the original matrix as a unit. I suspect there are many other ways of doing this, and would love to hear about them in the comments.

2 Responses to “How to do a matrix reshape by ‘blocks’”

  1. Matt Fig replied on :

    Here is one version of the obligatory one-liner.

    newMat=cell2mat(reshape(mat2cell(longMat,rSize*ones(1,n),cSize),5,4).');

    However, this is only significantly faster for large systems.

    I have written optimized, hard-to-read MATLAB code in the past, and in order to help those who might be reading it in the future I often put the straightforward FOR loop(s) version in the comments. This serves several purposes. Among them are that it lets any future user see more easily what is going on and quickly get to maintenance concerns.

    Thanks for another great video, Doug!

  2. Sean de Wolski replied on :

    And the obligatory one-liner without cells:

    %Some parameters
    blksz = 3; %block size in row/col
    nrep = 20; %block repetitions
    nr = 4; %number of rows of blocks
    nc = 5; %number of columns of blocks

    %Determinant sample data
    A = reshape(1:(blksz*blksz*nrep),blksz,[])’;

    %Engine one line version:
    NewA = reshape(permute(reshape(permute(reshape(A.’,blksz,blksz,[]),[2 1 3]),blksz,blksz*nc,[]),[2 1 3]),blksz*nc,blksz*nr)’;

    %Engine in pieces:
    B = reshape(A.’,blksz,blksz,[]); %reshape the transpose to 3d with each block a 3×3
    C = permute(B,[2 1 3]); %transpose each block
    D = reshape(C,blksz,blksz*nc,[]); %reshape to nr planes that need to be stacked vertically
    E = permute(D,[2 1 3]); %transpose each plane
    F = reshape(E,blksz*nc,blksz*nr)’; %reshape into a matrix and transpose

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


MathWorks

Doug Hull is a proud MathWorker who is on a mission to help you with MATLAB.

Doug's picture

These postings are the author's and don't necessarily represent the opinions of The MathWorks.