4

In MATLAB you can create an array of integers easily with

N = 100; % Number of points
A = 1:N; % row vector of 1,2,3,..., 100

If I want a column vector instead of a row vector, I can do that with

A = [1:N].';

Now, MATLAB warns me that

Use of brackets [] is unnecessary. Use parentheses to group if necessary.

Well, they are not unnecessary, because 1:N.' creates a row vector, as only the scalar N is transposed, as opposed to the full array.

I can of course suppress this message on that line, in that file, or in all files, but why does MATLAB throw this warning in the first place, as it seems that I can't do without those brackets in this case?

It turns out a large part of the confusion stems from the usage of American English by The MathWorks, as the rest of the English-speaking world uses the term brackets for () and the term square brackets for []. See Wikipedia

Adriaan
  • 17,741
  • 7
  • 42
  • 75

2 Answers2

5

As MATLAB warns you: Use parentheses to group if necessary. In your case it is necessary. You want .' to apply to 1:N, therefore use parentheses (). Square brackets [] are for collecting the elements within, but 1:N is already collected

A=(1:N).';
Solstad
  • 285
  • 1
  • 9
  • 1
    _square brackets on a collected array basically act as round brackets since the array is already collected_ My hunch is that, although they can be used that way, they probably slow things down (because of the concatenation / colllecting operation), compared to using round brackets – Luis Mendo Dec 08 '16 at 14:24
  • @LuisMendo I agree; extra square brackets is an operation. – Solstad Dec 08 '16 at 14:54
  • @LuisMendo that's probably the main reason MATLAB hands me this warning, because if there'd be no difference in execution time, there'd be no need of warning you to use different brackets/parentheses/however you want to call those. – Adriaan Dec 08 '16 at 15:46
4

The square brackets are used to declare arrays. However, MATLAB's syntax is built so that 1:n will already create an array.

[1:3] would then be equivalent to [[1 2 3]], which is why MATLAB's tells you that squares brackets are unnecessary in this case

This said, you definitely need to group your array declaration with parenthesis before transposing, due to operator precedence

BillBokeey
  • 3,168
  • 14
  • 28