In Haskell, if I wanted to get a 10 element list which only contained the number 5, I could do something like this:
take 10 $ repeat 5
Output:
[5,5,5,5,5,5,5,5,5,5]
Is there anything like this in Matlab?
Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.
It is easy to assign repeated values to an array:
x(1:10) = 5;
If you want to generate the array of elements inline in a statement try something like this:
ones(1,10) * 5
or with repmat
repmat(5, 1, 10)
The ones method is much faster than using repmat:
>> tic; for i = 1:1e6, x=5*ones(10,1); end; toc
Elapsed time is 3.426347 seconds.
>> tic; for i = 1:1e6, y=repmat(5,10,1); end; toc
Elapsed time is 20.603680 seconds.
And, in my opinion, makes for much more readable code.
Given a predefined m-by-n
matrix size and the target value val
, in your example:
m = 1;
n = 10;
val = 5;
there are currently 7
different approaches that come to my mind:
1) Using the repmat function (0.094066 seconds)
A = repmat(val,m,n)
2) Indexing on the undefined matrix with assignment (0.091561 seconds)
A(1:m,1:n) = val
3) Indexing on the target value using the ones function (0.151357 seconds)
A = val(ones(m,n))
4) Default initialization with full assignment (0.104292 seconds)
A = zeros(m,n);
A(:) = val
5) Using the ones function with multiplication (0.069601 seconds)
A = ones(m,n) * val
6) Using the zeros function with addition (0.057883 seconds)
A = zeros(m,n) + val
7) Using the repelem function (0.168396 seconds)
A = repelem(val,m,n)
After the description of each approach, between parentheses, its corresponding benchmark performed under Matlab 2017a
and with 100000
iterations. The winner is the 6th
approach, and this doesn't surprise me.
The explaination is simple: allocation generally produces zero-filled slots of memory... hence no other operations are performed except the addition of val
to every member of the matrix, and on the top of that, input arguments sanitization is very short.
The same cannot be said for the 5th
approach, which is the second fastest one because, despite the input arguments sanitization process being basically the same, on memory side three operations are being performed instead of two:
1
val
See repmat in the documentation.
B = repmat(5,1,10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With