Is giving a space after comma in functions the convention?

7 ビュー (過去 30 日間)
Snoopy
Snoopy 2024 年 9 月 25 日
編集済み: James Tursa 2024 年 9 月 25 日
I more often see
y = pdf('t', x, df);
than
y = pdf('t',x,df);
That is, people often give a space after comma when writing the input arguments in a function. But then when indexing from an array like
array(1,2)
they do not do this. I also see this happening in books. So is this indeed a convention? If not, what is the comvention? Or are both just a matter of preference. But I doubt that preference is the case because I consistently see the above happening.
  3 件のコメント
DGM
DGM 2024 年 9 月 25 日
Don't take this as an authoritative answer, but I'll point out that in cases like this:
x = pdf('t', x, df);
... the spaces don't really do anything. The thing that separates the arguments is the comma.
However, in cases like this
y = [1 3 5; 7 9 11];
... spaces actually can act as separators equivalent to a comma, so that would be the same as
y = [1,3,5;7,9,11];
or
y = [1, 3, 5; 7, 9, 11]; % extra spaces don't matter
That is, spaces (and linebreaks!) can potentially be used differently during array concatenation than during the construction of a comma-separated list.
With that in mind, I could see why a book might at least avoid writing something like:
% this is also the same thing
y = [1 3 5
7 9 11];
... simply for matters of clarity. It's much more explicit to have the commas and semicolons in place, even if they mean the same thing.
I have no room to comment on best spacing practices.
Snoopy
Snoopy 2024 年 9 月 25 日
編集済み: Snoopy 2024 年 9 月 25 日
Thanks for these and the answers below.

サインインしてコメントする。

回答 (3 件)

Voss
Voss 2024 年 9 月 25 日
編集済み: Voss 2024 年 9 月 25 日
Both are matters of preference.

Star Strider
Star Strider 2024 年 9 月 25 日
Leaving the space improves readabiity, so I usually do it. In reality, it doesn’t make any difference.

James Tursa
James Tursa 2024 年 9 月 25 日
編集済み: James Tursa 2024 年 9 月 25 日
A MATLAB specific thing that is somewhat related is that spacing is important in concatenation. E.g., the following look similar but in fact can do different things because of how the parser works.
[1+2,3+4]
ans = 1×2
3 7
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
[1 +2, 3 +4]
ans = 1×4
1 2 3 4
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
[1+ 2, 3+ 4]
ans = 1×2
3 7
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
[1 + 2, 3 + 4]
ans = 1×2
3 7
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
In the second example above, the space is treated as a comma. Just something to be aware of.

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by