I would like to know what is the best way to retrieve the number of element in a vector in matlab in term of speed:
is it:
length(A)
or
size(A,1)
Neither. You want to always use numel
for this purpose. length
only returns the longest dimension (which can get confusing for 2D arrays) and size(data, dimension)
requires you to know whether it's a row or column vector. numel
will return the number of elements whether it is a row vector, column vector, or multi-dimensional array.
We can easily test the performance of these by writing a quick benchmark. We will take the size with the various methods N
times (for this I used 10000).
function size_test
nRepeats = 10000;
times1 = zeros(nRepeats, 1);
times2 = zeros(nRepeats, 1);
times3 = zeros(nRepeats, 1);
for k = 1:nRepeats
data = rand(10000, 1);
tic
size(data, 1);
times1(k) = toc;
tic
length(data);
times2(k) = toc;
tic
numel(data);
times3(k) = toc;
end
% Compute the total time required for each method
fprintf('size:\t%0.8f\n', sum(times1));
fprintf('length:\t%0.8f\n', sum(times2));
fprintf('numel:\t%0.8f\n', sum(times3));
end
When run on my machine it yields:
size: 0.00860400
length: 0.00626700
numel: 0.00617300
So in addition to being the most robust, numel
is also slightly faster than the other alternatives.
That being said, there are likely many other bottlenecks in your code than determining the number of elements in an array so I would focus on optimizing those.