08.19.06
Efficient Matlab Programming using REPMAT
Unlike Java and C/C++, Matlab has its own way of performing your codes because it uses its own pre-compiled codes, therefore users need not compile the source beforehand. To write efficient MATLAB codes, one has to understand the underlying fundamentals that builds up MATLAB itself. For instance, MATLAB is catered more for matrix computations and analysis, rather than coding an executable program, although the latter is still possible. Nonetheless, if you want to write a .exe program, you might be better off playing with C/C++ instead.
So, where does MATLAB supremacy comes in? As mentioned in the previous paragraph, it is good when it comes to matrix operations. For instance, “dot-product” operations, the “\” operations, and those that uses linear algebra operations. In particular, I will focus more on using REPMAT to exploit MATLAB’s engine in this post.
What does REPMAT means? Simply, it means to replicate and tile an array. To give a simple overview, for instance, if you want a vector row containing “8″, or a column vector containing “10″, respectively,
repmat(8,[1 100])
repmat(10,[5 1])
The first line will produce 100 entries of “8″ in a row vector, and the second line produces 5 entries of “10″ in a column vector. i.e.,
[8 8 8 8 …… 8]
[10]
[10]
[10]
[10]
[10]
This sounds very simple and straightforward. Let’s get more complicated by introducing column vector, “x”, such that the entries of x contains your own data values. For example, we want to repeat the same x over 3 columns, then the commandline is,
repmat(x,[1 3])
The main idea here is pretty much clear. Instead of using FOR command to iteratively create several rows or columns of the same vectors, REPMAT is the way to use in MATLAB. Below is the product information given by MATLAB:
REPMAT Replicate and tile an array.
- B = repmat(A,M,N) creates a large matrix B consisting of an M-by-N tiling of copies of A. The size of B is [size(A,1)*M, size(A,2)*N].
- B = REPMAT(A,[M N]) accomplishes the same result as repmat(A,M,N).
- B = REPMAT(A,[M N P …]) tiles the array A to produce a multidimensional array B composed of copies of A. The size of B is [size(A,1)*M, size(A,2)*N, size(A,3)*P, …].
- REPMAT(A,M,N) when A is a scalar is commonly used to produce an M-by-N matrix filled with A’s value and having A’s CLASS. For certain values, you may achieve the same results using other functions. Namely,
REPMAT(NAN,M,N) is the same as NAN(M,N)
REPMAT(SINGLE(INF),M,N) is the same as INF(M,N,’single’)
REPMAT(INT8(0),M,N) is the same as ZEROS(M,N,’int8′)
REPMAT(UINT32(1),M,N) is the same as ONES(M,N,’uint32′)
REPMAT(EPS,M,N) is the same as EPS(ONES(M,N))- Example:
repmat(magic(2), 2, 3)
repmat(uint8(5), 2, 3)
If you are an avid MATLAB user and always working with matrices, you should always try to use REPMAT as much as possible, avoiding possible loop operations, such as FOR or WHILE.