An elegant way to create an array full of one number in MATLAB?
Some alternatives:
-
Usage
repmat
:A = repmat(3, [5 7]); %// 5x7 matrix filled with the value 3
-
Using indexing:
A(1:m, 1:n) = x;
Below is a comparison of the time between all the proposed approaches. As you can see @Dennis' are the fastest (at least on my system).
Functions:
function y = f1(x,m,n) %// Dennis' "ones"
y = x*ones(m,n);
function y = f2(x,m,n) %// Dennis' "zeros"
y = x+zeros(m,n);
function y = f3(x,m,n) %// Luis' "repmat"
y = repmat(x,[m n]);
function y = f4(x,m,n) %// Luis' "dirty"
y(m,n) = 0;
y(:) = x;
function y = f5(x,m,n) %// Luis' "indexing"
y(1:m,1:n) = x;
function y = f6(x,m,n) %// Divakar "matrix porod"
y = x*ones(m,1)*ones(1,n);
Benchmarking script for square arrays:
x = 3;
sizes = round(logspace(1,3.7,10)); %// max limited by computer memory
for s = 1:numel(sizes)
n = sizes(s);
m = sizes(s);
time_f1(s) = timeit(@() f1(x,m,n));
time_f2(s) = timeit(@() f2(x,m,n));
time_f3(s) = timeit(@() f3(x,m,n));
time_f4(s) = timeit(@() f4(x,m,n));
time_f5(s) = timeit(@() f5(x,m,n));
time_f6(s) = timeit(@() f6(x,m,n));
end
loglog(sizes, time_f1, 'r.-');
hold on
loglog(sizes, time_f2, 'g.:');
loglog(sizes, time_f3, 'b.-');
loglog(sizes, time_f4, 'm.-');
loglog(sizes, time_f5, 'c.:');
loglog(sizes, time_f6, 'k.:');
xlabel('Array size')
ylabel('Time')
legend('ones', 'zeros', 'repmat', 'dirty', 'indexing', 'matrix prod')
For column arrays: just change the following lines:
sizes = round(logspace(1,3.7,10)).^2; %// max limited by computer memory
n = 1;
m = sizes(s);
For arrays of strings:
sizes = round(logspace(1,3.7,10)).^2; %// max limited by computer memory
n = sizes(s);
m = 1;
Results for a dual core processor, 2 GB RAM, Windows Vista, Matlab R2010b:
- Square arrays;
- arrays of columns;
- Arrays of strings.
source to share
There are two main ways to do this:
A = ones(10,1)*3
B = zeros(10,1)+3
The first one is most often used in examples, but if I'm not mistaken, the second one works a little better. In general, this is just a matter of taste.
Of course, if you have an existing matrix, there is another easy way:
C = zeros(10,1)
C(:) = 3;
And for completeness, the repmat solution suggested by @Luis is also great.
source to share
Alternatively, one can use a method matrix multiplication
(which should be pretty fast based on MATLAB) for assignment 2D
or multidimensional array
.
So, counting m
how rows
, n
how columns
and x
how the value to be assigned to all elements, the code would be -
y = x*ones(m,1)*ones(1,n);
source to share