Is there a meaningful guideline on when to use parentheses vs square brackets vs curly brackets in writing MatLab code?

207 visualizzazioni (ultimi 30 giorni)
Is there a meaningful guideline on when to use parentheses vs square brackets vs curly brackets in writing MatLab code? I looked in the FAQ and did not see answers. After completing a handful of MatLab courses I thought I had some understanding, but I also see code that convinces me that I do not know the answer. (Use square brackets for concatination of strings.....but not always? Defining a vector can use parentheses OR square brackets? but not always? Indexing can use parentheses OR square brackets? ...but not always? To pass a value to a function use parentheses? Matrix concatenation use square brackets? To construct matrix use square brackets? Plot functions use parentheses?
  2 Commenti
DGM
DGM il 13 Set 2024
I think @Voss makes a very good point. We can give references and general explanations, but if you have specific cases that you find confusing, it may be particularly helpful to have them explained. In a lot of cases, there is more than one thing going on in a single line of code.
Stephen23
Stephen23 il 14 Set 2024
Modificato: Stephen23 il 14 Set 2024
"Use square brackets for concatination of strings....?"
If you want to concatenate string arrays (or any other type of array) then of course you can use square brackets.
Because square brackets are the concatenation operator.
Note that text comes in two major flavors, string arrays (here a scalar string array):
s = "hello world"
s = "hello world"
size(s)
ans = 1×2
1 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
and character arrays (here a character vector):
v = 'hello world'
v = 'hello world'
size(v)
ans = 1×2
1 11
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
They have very different properties and behaviors:
"Defining a vector can use parentheses OR square brackets?"
This is a very common misunderstanding about MATLAB, which does really not have a vector defining operator in the sense that you mean (certainly parentheses (a grouping operator) will not help you with this), partly because it does not have a special vector type. Note that vectors are just arrays, and therefore may be defined by concatenating arrays (i.e. vectors or scalars aka numbers) together using square brackets.
Because square brackets are the concatenation operator.
"Indexing can use parentheses OR square brackets?"
If your courses used square brackets to perform indexing then you need to ask them for your money back.
MATLAB indexing fits generally into these two types:
  • () parentheses to refer to the array itself.
  • {} curly braces to refer to the array content (for container types only)
"To pass a value to a function use parentheses?"
Yes.
"Matrix concatenation use square brackets?"
All concatenation uses square brackets (see "defining a vector" above). Or CAT, HORZCAT, VERTCAT, etc.
Because square brackets are the concatenation operator.
"To construct matrix use square brackets?"
Yes, any matrix (i.e. 2D array) incuding vectors (which are just matrices after all) and scalars (although this is usually not useful) may be defined by concatenating other arrays (incuding scalar ones i.e. numbers) together. That is how MATLAB works. Everything is an array. Concatenation uses square brackets.
Because square brackets are the concatenation operator.
"Plot functions use parentheses"
Calling any function function uses parentheses, not just plotting:
cos(pi)
ans = -1
Looking over your list of specific questions, most of your confusion seems to relate to array concatenation. Perhaps this confusion is based on experience with other languages, thus you are seeking different special operators for different special data types e.g. scalars, vectors, matrices, etc. In MATLAB these differences simply do not exist. MATLAB has concatenation of arrays using square brackets. That is it.
What beginners often fail to understand is that in MATLAB everything is an array:
Special names e.g. "scalar" or "matrix" or "vector" are purely for the humans reading the text, they do not indicate different data types or differences in memory or ways of creating them. Only the array size is different. Buts still arrays!
This is an array (a scalar one, aka a number):
a = 3
a = 3
Here I concatenate three (scalar) arrays together to make a larger array:
b = [1,2,9]
b = 1×3
1 2 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Here I concatenate several arrays together to make a larger array (a matrix):
c = [0,0,a;b]
c = 2×3
0 0 3 1 2 9
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Beginners often confuse themselves because they are incorrectly imagine that all of these things (creating vectors, creating matrices) are all different operations that require different magic incantations (because that is how language X does it). In MATLAB they are fundamentally all the same thing: concatenating arrays together using square brackets.
LIkewise, once you understand that numbers are just scalar arrays which are not a special class or type (they are just the same as any other array) then concatenating any arrays (e.g. scalars) together to make larger arrays (e.g. vectors, matrices) is a very simple concept to work with.
Do not search for differences (because that is how language X does it) that do not exist, otherwise you will just confuse yourself.

Accedi per commentare.

Risposta accettata

Steven Lord
Steven Lord il 14 Set 2024
Parentheses
Generally speaking, using parentheses to index into a variable usually does one of two things.
  • If the variable is something that "gets evaluated" it is used to evaluate the object. Examples of this include function handles, the objects created by the memoize function from a function handle, scatteredInterpolant objects (where "evaluation" is interpolation), and cfit objects from Curve Fitting Toolbox. Generally you can't create arrays of these types of objects, they must be scalar objects. [The ability to evaluate takes precedence over the ability to create arrays and extract sub-arrays.]
fh = @sin
fh = function_handle with value:
@sin
functionHandleEvaluatedAtPoints = fh(1:5)
functionHandleEvaluatedAtPoints = 1×5
0.8415 0.9093 0.1411 -0.7568 -0.9589
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
load census
cfitobj = fit(cdate, pop, 'poly2')
cfitobj =
Linear model Poly2: cfitobj(x) = p1*x^2 + p2*x + p3 Coefficients (with 95% confidence bounds): p1 = 0.006541 (0.006124, 0.006958) p2 = -23.51 (-25.09, -21.93) p3 = 2.113e+04 (1.964e+04, 2.262e+04)
populationIn1955 = cfitobj(1955) % Evaluate fit at x = 1955
populationIn1955 = 168.4030
plot(cfitobj)
hold on
plot(1955, populationIn1955, 'o')
  • Otherwise indexing with parentheses generally returns something of the same class as the thing you're indexing into. So if you use parentheses to index into a double array you get a double array out, using them to index into a cell array gives you a cell array, using them to index into a table array gives you a table array, etc.
Parentheses are also used when defining and evaluating functions to contain the input arguments or to override/clarify to users operator precedence.
x1 = 2*3+1 % multiply first then add
x1 = 7
x2 = 2*(3+1) % add first then multiply
x2 = 8
x3 = (2*3)+1 % Not necessary for MATLAB but could remind users multiply first then add
x3 = 7
Curly braces
"Container" types (like table arrays and cell arrays) that are meant to store potentially disparate types of data often define curly brace indexing to extract the contents from the container rather than the container itself. So if you have a table:
t = array2table(magic(4))
t = 4x4 table
Var1 Var2 Var3 Var4 ____ ____ ____ ____ 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1
indexing with parentheses gives you another table
smallerTable = t(1:2, 2:4)
smallerTable = 2x3 table
Var2 Var3 Var4 ____ ____ ____ 2 3 13 11 10 8
while indexing with curly braces gives you (in this case) a double array since that's what the table contains.
doubleArray = t{1:2, 2:4}
doubleArray = 2×3
2 3 13 11 10 8
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Curly braces are also used to create cell arrays.
fruits = {'apple', 'banana', 'cherry'}
fruits = 1x3 cell array
{'apple'} {'banana'} {'cherry'}
Square brackets
Square brackets generally are used for one of two things: concatenting arrays together or to delimit multiple outputs of a function definition or function call. [They can also be used for deleting sections of an array.]
concatenationExample = [1:10; 11:20]
concatenationExample = 2×10
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
[U, S, V] = svd(magic(4)); % indicating svd is called with 3 outputs

Più risposte (4)

Jatin
Jatin il 13 Set 2024
In MATLAB, parentheses, square brackets, and curly braces serve distinct purposes depending on the context. Your confusion is understandable, but it can be resolved by reviewing the relevant documentation, which explains how each is used in different situations.
  • Paranthesis
  • Square Brackets
  • Curly Braces
Hope this helps!

Voss
Voss il 13 Set 2024
Modificato: Voss il 13 Set 2024
If you share a particular snippet of code that is confusing, someone here can probably explain it. (Of course, that code may be written incorrectly.)
Here are some references that briefly explain when to use parentheses, square brackets, and curly braces, respectively:
To answer your other questions:
"Indexing can use parentheses OR square brackets? ...but not always?"
Indexing uses parentheses.
"To pass a value to a function use parentheses?"
Yes.
"Matrix concatenation use square brackets?"
Yes.
"To construct matrix use square brackets?"
It depends on what you mean by "construct", but if you mean to concatenate scalars (or row vectors or column vectors or matrices) together to form a matrix, then yes, use square brackets.
"Plot functions use parentheses?"
Yes. Passing arguments to any function uses parentheses.
"Defining a vector can use parentheses OR square brackets? but not always?"
Again, it depends on what you mean by "defining", but if you mean to concatenate scalars (or smaller vectors) together to form a vector, then use square brackets.
"Use square brackets for concatination of strings.....but not always?"
In this case, it depends on what you mean by "strings" because there are strings and there are character vectors (which are sometimes called "strings" mostly in old references, since they pre-date the actual string class). To concatenate strings, use the + operator, e.g.:
str1 = "string1";
str2 = "string2";
result = str1 + str2
result = "string1string2"
To concatenate character vectors, use square brackets (same as with any other data type):
C1 = 'char1';
C2 = 'char2';
result = [C1 C2]
result = 'char1char2'
Note that if you use square brackets to concatenate strings, the result is consistent with any other data type: you get the string array that results from concatentating the individual strings (which are really scalar string arrays themselves):
result = [str1 str2]
result = 1x2 string array
"string1" "string2"
So the choice of square brackets or + with actual strings depends on what result you want.
  1 Commento
Stephen23
Stephen23 il 14 Set 2024
Modificato: Stephen23 il 14 Set 2024
+1 Also very useful (has links to the pages given in this answer):
"To concatenate strings..."
Concatenating string arrays is always done using square brackets, just like any other array type. The operation performed by (overloaded) PLUS is quite distinct, and is named append:
AFAIKT, use of the term concatenate for every operation is one of the causes of this confusion.

Accedi per commentare.


Matt J
Matt J il 14 Set 2024
Modificato: Matt J il 14 Set 2024
General
If we forget about indexing for the moment, it becomes very simple. Function calls use parentheses, and only parentheses,
output=myfunction(input1,input2)
Concatentation, of any Matlab variable type, uses square brackets and only square brackets,
largerArray=[smallerArray1, sammerArray2,smallerArray3];
And that's pretty much it. There is nothing more to know about (),[],{} when you take indexing out of the equation.
Indexing
With indexing, the thing to understand is that each Matlab variable type has its own indexing rules and syntax. Matrices and numeric arrays can use only parentheses. Cell arraysand tables can use parentheses () or braces {} depending on the nature of lookup that you are trying to do. Structures can use parentheses () or dot indexing. There are good reasons for these differences, but the bottom line is, you must refer to the documentation on a particular variable type to know its indexing sytnax.

Image Analyst
Image Analyst il 13 Set 2024
@Jerome yes there is. If you look at this FAQ entry:
I think that it gives a pretty good intuitive idea about when to use each:
  1. when to use braces { }
  2. when to use brackets [ ]
  3. when to use parentheses ( )

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Prodotti


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by