tags:

views:

218

answers:

4

I swear I used to know, but this is hard to look up: what do the end-of-line commas do in Matlab? In the couple of small tests I've done, they don't seem to make the code behave any different. I'd like to know because they're all over in this code I didn't write (but have to maintain).

Examples of what I mean:

if nargin<1,
    % code
end

if isError,
    % code
end

try,
    % code
    while 1,
        % even more code
    end
catch,
    % code
end
+1  A: 

I think the comma in matlab is like the semicolon in C. It separates commands, so you can put multiple commands in one line separated by commas.

The way your program is written, I believe the commas make no difference.

3lectrologos
+3  A: 

If you read tightly coded m-files (e.g., many of the built-in MATLAB functions) you will discover a variant of the if ... end construct that is written on one line. Here's an example
if x<0, disp('imaginary'); end
Notice the comma between the x<0 and the disp(...). Apparently the comma tells the MATLAB interpretter that the conditional test has ended. To my knowledge this is only place where a statement (OK, part of a statement) ends with a comma. It's just one of those quirks that true believers come to use without hesitation.

http://web.cecs.pdx.edu/~gerry/MATLAB/programming/basics.html

Albert
But if there's a line break, it's just superfluous, correct?
Benjamin Oakes
+9  A: 

According to the documentation for the comma character in MATLAB, one of its functions is to separate statements within a line. If there is only one statement on a line, the comma is not needed. I don't like to see it there, although I know some people write code that way.

Steve Eddins
+6  A: 

As others have pointed out, commas at the end of a line are unnecessary. They are really just for separating statements that are on the same line. MLINT and the Editor will even give you a warning if you use one without needing it:

alt text

>> mlint comma_test.m
L 1 (C 4): Extra comma is unnecessary.
gnovice
Haha, I guess that's what you get for using `vim` to edit Matlab code... I had something to use MLINT with it. Might have to give that a try now.
Benjamin Oakes

related questions