1

In MATLAB, brackets([ and ]) are used for matrices, whose elements have an identical type. Braces({ and }) are used for cell arrays, whose elements can (and usually do) have different types.

However, the definition of a function in MATLAB uses brackets:

function [A, B, C] = func(x, y, z)
    A = length(x) + 1i * length(y);
    B = zeros(size(y));
    C = int2str(z);
end

Here, A is a complex number, B is a matrix, and C is a string.
Why does this so? Why not braces for this like:

function {A, B, C} = func(x, y, z)
    A = length(x) + 1i * length(y);
    B = zeros(size(y));
    C = int2str(z);
end

which causes a compile error (I mean, a syntax error).

Naetmul
  • 14,544
  • 8
  • 57
  • 81
  • 3
    Because it is how the syntax is defined. MATLAB does not create a matrix or a cell there, it is just using brackets for something else. Why does MATLAB use `;` to stop code output, but also to define columns in matrices? Why use `end` to finish a function, but also a `for` loop? Because it is how they defined the language. – Ander Biguri May 22 '17 at 12:04

1 Answers1

1

Much of MATLAB's language semantics, constructs and functionality are the result of design decisions that would make the language easier to grasp for scientists and engineers. Some of these features have since remained there for historical/compatibility reasons. Analogously, one can also argue about the fact that MATLAB uses parentheses () for function calls as well as indexing, which to some could be an even more questionable choice. Also, you can index a cell array with both parentheses () and curly braces {}.

As MathWorks website states:

Square brackets enable array construction and concatenation, creation of empty matrices, deletion of array elements, and capturing values returned by a function

Note that MATLAB was initially developed as matrix library providing wrappers for LINPACK, EISPACK and the likes. As a result it only supported matrices and multi-dimensional arrays. Cells were introduced later to establish a good interoperability with other (possibly doubly linked-lists) data structures such as Java arrays and .NET array, and by the time they came, square brackets [] were already in-place for capturing return values of a function. Note that, MATLAB matrices are used much more widely compared to cell arrays and arguably using [] for capturing return values makes more sense from an API consistency point of view for MathWorks.

On a side note, it is worth mentioning that C++17 with structured bindings went the same route as MATLAB and there was much of debate on the topic of choosing [] over {}. This is also discussed in SO here.

Community
  • 1
  • 1
romeric
  • 2,325
  • 3
  • 19
  • 35