필터 지우기
필터 지우기

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

조회 수: 5 (최근 30일)
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.

채택된 답변

Walter Roberson
Walter Roberson 2017년 5월 31일
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
Walter Roberson
Walter Roberson 2017년 5월 31일
>> linspace(1,5,4)
ans =
1 2.33333333333333 3.66666666666667 5
You can see that it does create 4 points. The first of the points is always a, and the last of the points is always b
The points created by linspace() are always different (unless a == b, or unless a or b are infinity or NaN.) However, after round() the points might not be different, if the number of points requested is larger than the integer difference abs(b-a). For example round(linspace(1,2,4)) is [1 1 2 2] because you asked for too many points relative to the difference between 1 and 2.
I call linspace() with N+1 points; then the diff() reduces that to N values.
"Is the diff function used to specify a difference of 1 in the number of rows?"
No. The round() of linspace calculates the starting and stopping points of each sub-division. Then the diff() turns the start and stop locations into the length of each segment. mat2cell() needs to know the length of each segment.
In the special case where you want to break your image up into individual rows, you can use
mat2cell(YourImage, ones(1, size(YourImage,1)), size(YourImage,2), size(YourImage,3))

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

태그

Community Treasure Hunt

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

Start Hunting!

Translated by