# How to create a similar function as Matlab’s Repmat in R using kronecker

The repmat function comes with the Matlab package, however, it is also easy to replicate using R programmingâ€™s kronecker function. This means that you do not need to download an entire package for this single function, because you can make it yourself.

## Description

The repmat function from the Matlab package as the format of repmat(n,r,c) and it creates a matrix with r times the length of variable (n) rows, and c is the number of columns produced also replicating that variable. Replicating it requires using the kronecker function in the format of kronecker(matrix(1,r,c),n).

## Explanation

While the repmat function is part of the Matlab package, it can be replicated using the kronecker function. The Kronecker function uses the matrix argument, to replicate the values of the second argument. If set up correctly this function produces the same results as the repmat function. This allows you to use this function without downloading the entire package, since it is easy to replicate on your own.

## Examples

Here we have three examples of code creating a function similar to Matlab’s repmat function. In each case, the same function name is used and the function creating it is on the first line, with different input values in each example.

> repmat = function(n, r , c){kronecker(matrix(1,r,c),n)}
> a = 10
> repmat(a,2,3)
[,1] [,2] [,3]
[1,] 10 10 10
[2,] 10 10 10

This is a simple case using a single value and a fixed number of rows and columns.

> repmat = function(n, r , c){kronecker(matrix(1,r,c),n)}
> a = 1:5
> repmat(a,1,4)
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 2 2 2 2
[3,] 3 3 3 3
[4,] 4 4 4 4
[5,] 5 5 5 5

This example uses a vector with a fixed number of rows and columns entered. Note that despite entering one row, the vector still creates five rows because of the length of the vector, but also the four columns that were entered. It would actually duplicate the vector if the row argument was greater than one.

> repmat = function(n, r , c){kronecker(matrix(1,r,c),n)}
> t = as.numeric(Sys.time())
> set.seed(t)
> a = as.integer(abs(rnorm(1)*10))
> a
[1] 21
> x = as.integer(abs(rnorm(1)*5))
> x
[1] 4
> y = as.integer(abs(rnorm(1)*5))
> y
[1] 3
> repmat(a,x,y)
[,1] [,2] [,3]
[1,] 21 21 21
[2,] 21 21 21
[3,] 21 21 21
[4,] 21 21 21

This example enters random values into the function, demonstrating its general usability.

## Application

One useful application of the repmat function and the ability to replicate it is being able to set up a matrix of constant values for processing with another matrix or a data frame of the same size. This might be needed when they are being applied as arguments to a function that requires them to have the same size.

Being able to replicate a function that you do not otherwise have access to is a handy programming skill to have. This particular case serves as a good example.

Scroll to top