I bumped into this example trying to convert some julia to python and was surprised. In the example here, python and matlab give the same answer, while julia differs…

If you start with… X=rand(3,100) (and do X=mat(X) if in python)

what size should the result be and why? in python and matlab (and julia), X[1,:] will select a row. python and matlab however return a row vector (or a 1xN matrix) while julia returns a column vector (Nx1). there may be a reason, but I am not sure what that is. Is this expected?

Yup, there absolutely is a reason and it’s a doozy. It turns out that the embedding of one-dimensional containers into the algebra of matrices is not obvious. There are a number of choices you must make in how they behave, impacting everything from indexing to transposes. It’s one of the few design decisions that has had so much thought put into it that many Julia folk who have been around for a while have it memorized (#4774). It’s spawned a paper (still a draft) and presentations. There’s even an :4774: emoji commemorating its author and major thought-leader here and on Slack.

The end-result, though, is a remarkably simple rule: The resulting dimensionality of an indexing expression is the sum of the dimensionalities of the indices. Or even more specifically, the resulting axes of an indexing expression is the concatenation of all the axes of all the indices used.

So that’s why X[1, :] is a 1-dimensional vector while X[[1], :] is a 1xN row matrix.

One thing to keep in mind, that may make this less weird, is that Julia does not return an Nx1 array, but simply an N vector (no ‘x1’). The distinction makes a difference.

Yes, we need to pester @jiahao to make his draft paper public; if I remember right he details the “universes” of reasonable ways you can get vectors to work with matrices. None are perfect.

very interesting. I can see the reason. I caught me by surprise because of the difference with matlab and python with matrix operations. python uses two data types (array and matrix) so the operations for matrix are a bit different. matlab only had matrix operations. at least now I can understand the logic. thanks!

yes it does. it make all operations 2d – so that you’re only doing matrix operations. in this way it behaves more like matlab, which is why it was introduced. you’re correct that for an array X[1,:] returns a flat array.