Is there a meaningful guideline on when to use parentheses vs square brackets vs curly brackets in writing MatLab code?
333 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
DGM
2024 年 9 月 13 日
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
2024 年 9 月 14 日
編集済み: Stephen23
2024 年 9 月 14 日
"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"
size(s)
and character arrays (here a character vector):
v = 'hello world'
size(v)
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)
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
Here I concatenate three (scalar) arrays together to make a larger array:
b = [1,2,9]
Here I concatenate several arrays together to make a larger array (a matrix):
c = [0,0,a;b]
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.
採用された回答
Steven Lord
2024 年 9 月 14 日
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
functionHandleEvaluatedAtPoints = fh(1:5)
load census
cfitobj = fit(cdate, pop, 'poly2')
populationIn1955 = cfitobj(1955) % Evaluate fit at x = 1955
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
x2 = 2*(3+1) % add first then multiply
x3 = (2*3)+1 % Not necessary for MATLAB but could remind users multiply first then add
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))
indexing with parentheses gives you another table
smallerTable = t(1:2, 2:4)
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}
Curly braces are also used to create cell arrays.
fruits = {'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]
[U, S, V] = svd(magic(4)); % indicating svd is called with 3 outputs
0 件のコメント
その他の回答 (4 件)
Jatin
2024 年 9 月 13 日
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
Function Calls: https://www.mathworks.com/help/releases/R2021b/matlab/learn_matlab/calling-functions.html
Mathematical Expressions: https://www.mathworks.com/help/releases/R2021b/matlab/operators-and-elementary-operations.html
- Square Brackets
Creating Matrices and Arrays: https://www.mathworks.com/help/releases/R2021b/matlab/learn_matlab/matrices-and-arrays.html
Concatenation of Arrays: https://www.mathworks.com/help/releases/R2021b/matlab/math/creating-and-concatenating-matrices.html
String Arrays: https://www.mathworks.com/help/releases/R2021b/matlab/matlab_prog/create-string-arrays.html
- Curly Braces
Indexing Cell Arrays: https://www.mathworks.com/help/releases/R2021b/matlab/matlab_prog/access-data-in-a-cell-array.html
Hope this helps!
0 件のコメント
Voss
2024 年 9 月 13 日
編集済み: Voss
2024 年 9 月 13 日
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
To concatenate character vectors, use square brackets (same as with any other data type):
C1 = 'char1';
C2 = 'char2';
result = [C1 C2]
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]
So the choice of square brackets or + with actual strings depends on what result you want.
1 件のコメント
Stephen23
2024 年 9 月 14 日
編集済み: Stephen23
2024 年 9 月 14 日
+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.
Matt J
2024 年 9 月 14 日
編集済み: Matt J
2024 年 9 月 14 日
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.
0 件のコメント
Image Analyst
2024 年 9 月 13 日
@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:
- when to use braces { }
- when to use brackets [ ]
- when to use parentheses ( )
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!