How to divide a matrix into a variable number of smaller matrices?

11 views (last 30 days)
My task is to divide an image into smaller parts. The dimensions of the image will be variable and I need to divide the image by the rows i.e. the smaller parts will have the same number of columns as the original. The number of parts, n, to be divided into will be user input.
I can use the mat2cell function but I am stuck at how to give the number of rows there since that's variable. Please help.

Accepted Answer

Walter Roberson
Walter Roberson on 31 May 2017
number_of_rows = size(YourImage,1);
N = input('Number of pieces to break into');
rowgroups = diff( round(linspace(0, number_of_rows, N+1)) );
broken_up_image = mat2cell( YourImage, rowgroups, size(YourImage, 2), size(YourImage,3) );
The rowgroups calculation finds a way of breaking up the number of rows into the given number of pieces, being approximately fair in the distribution. For example if you ask to break 501 rows up into 16 pieces then you get [31 32 31 31 32 31 31 32 31 31 31 32 31 31 32 31]. There are other possible calculations, including distributing evenly except for the final one (which you could make either shorter or larger than the rest depending which way you round). For example perhaps you would prefer [31 * ones(1,15), 36], or [32 * ones(1,15), 21]
  3 Comments

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!