'Nother simple question: Constructing Vectors vs. Arrays

286 views
Skip to first unread message

Stuart Brorson

unread,
Jul 30, 2012, 8:38:09 AM7/30/12
to juli...@googlegroups.com
Hello again,

I just noticed that the following creates a Vector:

[1, 2, 3, 4, 5] # Comma separated

Whereas this creates a 2 dimensional Array:

[1 2 3 4 5] # Space separated

I was caught off guard by this. I guess my experience with Matlab
made me expect that the two should return the same type of object.
(Yes, I understand that my expectations of Matlab behavior should not
dictate Julia's behavior.)

I do understand that Julia differentiates between vectors and matrices
(and higher dimensional objects), and that's fine. I was just
wondering if the above behavior was "by design", or was an
unintentional by-product of some other design decision. If the
behavior is "by design", what's the best way to think about it -- that
is, how should one "intuit" the above behavior?

Stuart

John Myles White

unread,
Jul 30, 2012, 9:40:08 AM7/30/12
to juli...@googlegroups.com
This behavior is indeed by design.

The intuition is that you should focus on building up column vectors rather than row pseudo-vectors, so the most natural notation is the one that produces the type you probably want to use. But there's still notation that allows you to produce the other type when you desire.

There is a description of this notation in the manual, along with details about constructing matrices using notation like

A = [1 2 3; 4 5 6]

which produces a 2x3 matrix. Your example is just a 1x3 matrix, but Julia avoids letting special cases win out in defining syntax.

-- John
> --
>
>
>

Stefan Karpinski

unread,
Jul 30, 2012, 10:20:33 AM7/30/12
to juli...@googlegroups.com
The motivation behind this is actually that [1,2,3] should create a 1d vector as someone coming from Python or Ruby (or JavaScript or ...) would expect, and 1d vectors are compatible with column matrices, so this is "vertical" rather than horizontal. [1 2 3] on the other hand needs to be horizontal and create a row matrix for Matlab compatibility, especially so that you can do things like input a matrix like this:

[1 2 3
 4 5 6]

These conflicting requirements leave us in a bit of bind. The current design is an attempt to give reasonably intuitive behavior for both kinds of programming: general programming and linear algebra. You can use commas to input lists of things for general programming; you can use spaces and newlines (or semicolons) for inputing vectors and matrices. To try to avoid further confusion, mixing the two input modes is not allowed:

julia> [1,2,3;4,5,6]
unexpected semicolon in array expression

julia> [1,2,3
        4,5,6]
missing separator in array expression

You can't mix commas with semicolons or newlines.

--




Reply all
Reply to author
Forward
0 new messages