The square brackets impede the boundary checks when the vector is used for indexing:
x = zeros(1, 10000);
tic
for k = 1:10000
x(1:k) = k;
end
toc
x = zeros(1, 10000);
tic
for k = 1:10000
x([1:k]) = k;
end
toc
tic
for k = 1:10000
v = 1:k;
x(v) = k;
end
toc
Elapsed time is 0.087256 seconds.
Elapsed time is 0.374184 seconds. !!! Factor 4 !!!
Elapsed time is 0.375447 seconds.
When Matlab accesses an array element, it has to check, if the index is inside the allowed range: > 0, < length, integer. It looks like Matlab performs this in x(1:k) only for 1 and k, while in x([1:k]) this test is applied to each element as in the 3rd case x(v).
A similar effect occurres for logical indexing: Matlab has to check only the size of the index vector once, not for each element.
tic
Lv = false(size(x));
for k = 1:10000
Lv(k) = true;
x(Lv) = k;
end
toc
Elapsed time is 0.176343 seconds.
It is plausible that this is slower than x(1:k), because the values of the mask Lv have to be considered. But it is much faster than x([1:k]) or the equivalent usage of an index vector.
Best Answer