MATLAB: Not use square brackets

anti-patternbracketscomplexm-lintsquare brackets

Why does Matlab suggest that I shouldn't use square brackets unless absolutely necessary? For example, if I type
x = [1:10];
the default code-checking feature suggests "Use of brackets [] is unnecessary. Use parentheses to group, if needed." I realize that the square brackets here are not necessary, but is there some cost to including them? Are parentheses more computationally efficient?

Best Answer

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; % <- [...] added
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.