How to increase or decrease granularity of a matrix?

I want to increase or decrease the granularity of a matrix by a scalar factor, which would look like this:
Increasing Granularity
Increasing the granularity of a matrix replicates elements to scale the size of the matrix up by an integer factor.
A = [1 2
  3 4]
B = increase(A, 2)
B = [1 1 2 2
  1 1 2 2
  3 3 4 4
  3 3 4 4]
Decreasing Granularity
Decreasing the granularity of a matrix averages together elements to scale the size of the matrix down by an integer factor.
C = [1 2 3 4
  5 6 7 8
  4 1 8 3
  6 7 2 5]
D = decrease(C, 2)
D = [(1+2+5+6)/4 (3+4+7+8)/4
  (4+1+6+7)/4 (8+3+2+5)/4]
D = [3.5 5.5
  4.5 4.5]
Is there a way to accomplish these workflows in MATLAB?

 Accepted Answer

Increasing Granularity
Increasing the granularity of a matrix can be accomplished by either of the following workflows (assuming A is the matrix from the Question):
B = repelem(A, 2, 2)
or 
B = kron(A, ones(2))
The "repelem" function is a more flexible version of the hypothetical "increase" function posed in the Question, since it allows a user to set different scale factors for each dimension of the matrix.
The documentation pages for these functions can be found here:
Decreasing granularity
Decreasing the granularity of a matrix can be accomplished by the following workflow (assuming C is the matrix from the Question):
C = [1 2 3 4
5 6 7 8
4 1 8 3
6 7 2 5]
[Xq,Yq] = meshgrid([1.5 3.5], [1.5 3.5]);
D = interp2(C, Xq, Yq)
The three-argument syntax of "interp2" treats the matrix "C" as lying on a grid, where the x-coordinate starts at 1 in the first column and increases rightward and the y-coordinate starts at 1 in the first row and increases downward. The call to "meshgrid" creates two matrices corresponding to the x- and y-coordinates of the interpolation query points for each of the quadrants of "C". Finally "interp2" interpolates "C" at those query points, scaling the size of the matrix down by 2. This process becomes challenging for scaling factors greater than 2, but is still possible. 
The documentation pages for these functions can be found here:

More Answers (0)

Categories

Find more on Interpolation in Help Center and File Exchange

Products

Release

R2023a

Community Treasure Hunt

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

Start Hunting!