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

조회 수: 12 (최근 30일)
Zhe Dong
Zhe Dong 2022년 1월 9일
댓글: Rik 2022년 1월 9일
For arrays in matlab, is there a difference between an array with comma and one without?
  댓글 수: 1
Stephen23
Stephen23 2022년 1월 9일
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).

댓글을 달려면 로그인하십시오.

채택된 답변

John D'Errico
John D'Errico 2022년 1월 9일
편집: John D'Errico 2022년 1월 9일
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
Zhe Dong
Zhe Dong 2022년 1월 9일
That's very helpful, thank you both!
Rik
Rik 2022년 1월 9일
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).

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by