What's the differene between [a,b] and [a b] in matlab?

For arrays in matlab, is there a difference between an array with comma and one without?

1 Kommentar

There is a very important difference:
  • a comma clearly shows the intent.
  • a space is unclear and liable to bugs (i.e. unary operators vs binary operators).

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

John D'Errico
John D'Errico am 9 Jan. 2022
Bearbeitet: John D'Errico am 9 Jan. 2022

1 Stimme

No difference. If a comma is used, then MATLAB catenates the elements horizontally. A space is equivalent to a comma.
In SOME circumstances, a comma can be more clear about your intentions, and it can insure what will happen. Good coding practice suggests always using a comma, as this makes it very clear what was intended. And good coding practice says you should use the form that is most easily read and followed, so that you can more easily debug your code later.
There are probably some circumstances (that I am not thinking up at this moment, but they will probably come to me later) where a space can be confusing or even ambiguous, and then you may not know how MATLAB will take it. So in general, use a comma to separate elements.

4 Kommentare

This answer is correct. One of the "some circumstance" cases is when folks combine poor coding practices, such as
a = 1;
b = 2;
% Compare with/without comma in silly and poor usage
[a, - b] % Poor use of space after unary negative sign, but gets expected result
ans = 1×2
1 -2
[a - b] % Gets different result if the comma is left out
ans = -1
Exactly. There are some cases where an ambiguous expression arises. And usually it seems to involve the addition or subtraction operators, since both of them also have unary forms. A comma is just a safer thing to use, because it makes your intention unambiguous. It also makes your code easier to read when you need to debug it. Ok, I have heard that others sometimes need to debug their code. Surely that never happens to me. ;-)
That's very helpful, thank you both!
There are more situations where ambiguous syntax can cause problems: in R2021a and later the code below results in a single value.
[1 -... % NB: no space between minus and ellipsis
2]
ans = -1
In older releases this resulted in [1,-2] (in GNU Octave it still does).

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Gefragt:

am 9 Jan. 2022

Kommentiert:

Rik
am 9 Jan. 2022

Community Treasure Hunt

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

Start Hunting!

Translated by