recipes : programming : Quickly creating large matrices

Problem

How do I quickly create a large matrix of 5s?

Solution

There are multiple ways of making such a matrix and some will be faster than others. Which is faster will depend upon the exact version of MATLAB that you're using. This is because different optimisations exist in different versions. If speed is critical for you, you should run tests to determine what will work best for you. Here are some examples:

%Build a 1000 by 1000 array of ones then multiply matrix by 5
tic, ones(1000,1000)*5; toc
>> Elapsed time is 0.005019 seconds

%Use repmat to replicate the number 5 to create the 1000 by 1000 array
tic, repmat(5,1000,1000); toc
>> Elapsed time is 0.030439 seconds

%Create an array called X and populate with 5s
tic, X(1:1000,1:1000)=5; toc
>> Elapsed time is 0.009826 seconds
Discussion

In this case the fastest option is the first one. The difference may not seem like much, but it adds up if you're doing this thousands of times.