Basic questions when migrating from matlab to julia

Hello all,

I have a Matrix

M = [1 2 3; 3 2 1]

In julia if i want to extract the first row of the matrix then i am using

M1 = M[1, :]

But since i am extracting 1st row then M1 should remain a row vector 1x3, but it isnt it becomes a column vector 3x1? How can i fix it? Thank you :slight_smile:

These are some options:

julia> m1 = M[1,:]'
1×3 adjoint(::Vector{Int64}) with eltype Int64:
 1  2  3

julia> m1 = reshape(M[1,:], 1, 3)
1×3 Matrix{Int64}:
 1  2  3
1 Like

Easiest option is index with a vector

julia> M = [1 2 3; 3 2 1]
2×3 Matrix{Int64}:
 1  2  3
 3  2  1

julia> M[[1], :]
1×3 Matrix{Int64}:
 1  2  3
1 Like

Hello all,

I am defining a vector like this

A = 1:9

A= A’ # A is row vector of 9 elements from 1:9

Now i am replacing 3 element of A, then i am doing

A[2] = 12 ( in matlab i can do this but in julia it is giveing me error)

But it is giving me error, Can anyone help me here?


In Matlab, everything is a matrix, and the default “vector” is a 1×n matrix (though not consistently).

In Julia, we have vectors, which are most similar to an n×1 matrix, but they are really a different animal. For most things, a vector is actually what you want, you’re probably expecting a matrix because that’s what Matlab uses. Try to get used to Julia instead.

1 Like

Even better:

M[1:1, :] 
1 Like

This is a UnitRange, which is immutable, it is not an ordinary Vector. Even after transposing, it’s still immutable. If you want to change an element, you must turn it into a Vector first:

A = collect(1:9) 
A[3] = 5 #ok 

Thank you so much :slight_smile: :slight_smile:

Perhaps newcomers can appreciate some explanation of what is going on here. Indeed, by defining A using the colon notation we get a variable that behaves like a vector (or array):

julia> A = 1:1000

julia> A[9]

The resulting type is actually very memory economical:

julia> sizeof(A)

The trick is that this “array” is not really stored as an array.

In contrast, using collect we transform the original variable into a true vector (array):

julia> B = collect(A)
1000-element Vector{Int64}:

Now, this is occupying a lot more memory:

julia> sizeof(B)

Obviously, every element of the vector is now stored in memory. Only this is equivalent to Matlab array.