1

I need to enlarge a matrix A to a matrix B with size n times the size of A. The values must be repeated, eg:

A size 2x3, n = 3, leads to B size 6x9:

Sample values:

A =  
1 2 3  
4 5 6  

Results with:

B =  
1 1 1 2 2 2 3 3 3    
1 1 1 2 2 2 3 3 3  
1 1 1 2 2 2 3 3 3  
4 4 4 5 5 5 6 6 6  
4 4 4 5 5 5 6 6 6   
4 4 4 5 5 5 6 6 6  

What is the fastest way to achieve that in Matlab?

Shai
  • 111,146
  • 38
  • 238
  • 371
Pedro77
  • 5,176
  • 7
  • 61
  • 91

2 Answers2

5

There is also the Kronecker Tensor Product (kron) function:

n = 3;
B = kron(A,ones(n));

B =

     1     1     1     2     2     2     3     3     3
     1     1     1     2     2     2     3     3     3
     1     1     1     2     2     2     3     3     3
     4     4     4     5     5     5     6     6     6
     4     4     4     5     5     5     6     6     6
     4     4     4     5     5     5     6     6     6
Benoit_11
  • 13,905
  • 2
  • 24
  • 35
2

If you have the Image Processing Toolbox you can easily do this using imresize with nearest neighbor interpolation.

A = [1 2 3; 4 5 6];

% Repeat each element 3 times in each direction
B = imresize(A, 3, 'nearest');

%   1     1     1     2     2     2     3     3     3
%   1     1     1     2     2     2     3     3     3
%   1     1     1     2     2     2     3     3     3
%   4     4     4     5     5     5     6     6     6
%   4     4     4     5     5     5     6     6     6
%   4     4     4     5     5     5     6     6     6

If you don't have the Image Processing Toolbox, you can use interp2 with nearest neighbor interpolation to do something similar.

scaleFactor = 3;


[xx,yy] = meshgrid(linspace(1, size(A, 2), size(A, 2) * scaleFactor), ...
                   linspace(1, size(A, 1), size(A, 1) * scaleFactor));


B = interp2(A, xx, yy, 'nearest');
Suever
  • 64,497
  • 14
  • 82
  • 101