difference in brackets (, [ or no brackets?

24 Ansichten (letzte 30 Tage)
Nahum Pang
Nahum Pang am 18 Okt. 2016
Kommentiert: Walter Roberson am 10 Mai 2023
I tried typing in a simple array
x= 0:2:10
x=[0:2:10]
x=(0:2:10)
they all give me the same answer whats the difference then?

Akzeptierte Antwort

James Tursa
James Tursa am 18 Okt. 2016
Bearbeitet: James Tursa am 18 Okt. 2016
0:2:10 produces a row vector of the numbers 0,2,4,6,8,10.
In the [0:2:10] and (0:2:10) versions, the [ ] and ( ) are simply redundant and unnecessary, since what is inside the [ ] and ( ) is already a row vector.
In general, if you have only one argument to the [ ] or ( ) like above, the [ ] or ( ) are unnecessary. If you have more than one argument, then the [ ] actually does something. E.g.
x = [0,2,4,6,8,10]
In this case there are actually 6 separate arguments to the [ ], so the [ ] does something in this case (concatenates the 6 inputs into a single row vector).
  1 Kommentar
Walter Roberson
Walter Roberson am 10 Mai 2023
(0:2:10) prioritizes the calculation of 0:2:10 . For example,
1 + 0:2:10
ans = 1×5
1 3 5 7 9
1 + (0:2:10)
ans = 1×6
1 3 5 7 9 11
The + operator normally has higher priority than the : operator, so 1 + 0:2:10 is interpreted as (1+0):2:10 which is 1:2:10
[0:2:10] builds the vector 0 2 4 6 8 10 in memory, but then calls the horzcat() operation, as if you had used horcat(0:2:10) . horzcat() with just a single input just returns the same input, so it is valid but uses time that is not productive.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Image Analyst
Image Analyst am 18 Okt. 2016
No difference - they're ignored. Only difference would be if you used braces {}, which would turn the result into a "cell". See the FAQ for info on that: http://matlab.wikia.com/wiki/FAQ#What_is_a_cell_array.3F

ogaba-oche david
ogaba-oche david am 10 Mai 2023
(a+A)/2 keeps telling error, when a = 8 and A = -2
  1 Kommentar
Steven Lord
Steven Lord am 10 Mai 2023
Not for me.
a = 8;
A = -2;
(a+A)/2
ans = 3
Please show us the full and exact text (everything in red) of the error message you received when you performed that operation. You may also want to show us more information about the variables a and A.
whos a A
Name Size Bytes Class Attributes A 1x1 8 double a 1x1 8 double

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by