What is the difference between ending lines with ellipses or without in literally written matrices?

Viewed 94

The basics

The regular way of writing matrices in MATLAB is the one-liner, like:

A = [3,2,1;2,1,3;1,3,2];

Breaking a command into several lines is done with 3 dots, like:

x = tan(...
    y);      % ie: x = tan(y);

The problem

Now, combining these two rules to write a matrix literally (to clearly see its structure) results in:

B = [3, 2, 1;...
     2, 1, 3;...
     1, 3, 2];

MATLAB (in scripts and functions) however also accepts this form:

C = [3, 2, 1;
     2, 1, 3;
     1, 3, 2];

The question

Are both ways of writing a matrix (B and C above) completely identical in terms of how MATLAB reads them? If there is a difference, should one be preferred over the other, and why?

EDIT: There are many ways writing a matrix in MATLAB, in one or on multiple lines, which all produce the same output. But is there one method that MATLAB understands best (i.e. minimum effort to understand the input properly)? Or is the effort on the program side always the same?


The reason why I ask: I just found myself using both methods in a single script, once to simply break a long line of numbers, once to to have a better view on the data.

1 Answers

Writing:

A = [3, 2, 1; 2, 1, 3; 1, 3, 2];

Or:

B = [3, 2, 1;...
     2, 1, 3;...
     1, 3, 2];

Or:

C = [3, 2, 1;
     2, 1, 3;
     1, 3, 2];

Or an even shorter way:

D = [3, 2, 1
     2, 1, 3
     1, 3, 2];

Are all completely identical. ; or line breaks are both used for separating matrix rows.

Simple test:

>> isequal(A,B)
ans =
  logical
   1

>> isequal(A,C)
ans =
  logical
   1

>> isequal(A,D)
ans =
  logical
   1

So, which is best?

Using ... and line breaks (and ;) is completely unnecessary, it is using line breaks and than overriding them with ... for no reason. It is actually like writing:

B = [3, 2, 1; 2, 1, 3; 1, 3, 2];

Using ; and line breaks is also unnecessary although it may be helpful adding ; if you will want in the future to make them one line. It may also look more clear (opinion based?)

Using no line breaks is quite common, it is more compact although may not look as nice.

To summarise: Using ... and line breaks (and ;) is unnecessary and maybe confusing. Other option are mainly opinion based.

Related