In MATLAB you could write 1:n. Is there something similar to this notation in Julia?
Yes, there is something very similar to Matlab's 1:n
in Julia. It's 1:n
.
There are some differences, though. Matlab's 1:n
creates a "row vector," which is important since Matlab iterates over columns. If you look at Matlab's 1:n
funny, it magically turns into a dense array that stores all its elements, but if you carefully avoid looking at it, I believe it can avoid allocating the space for it entirely — this is why Matlab's linter recommends (1:n)
instead of [1:n]
.
In contrast, Julia's 1:n
is a true column vector that always just uses two integers to define itself. The only time it'll actually store all its elements into memory is if you ask it to (e.g., with collect
). In nearly all cases, though, you can use it like a real vector without storing its results; it'll very efficiently generate its elements on the fly. It may look a little strange since it just prints out as 1:n
, but it really is an array. You can even do linear algebra with it:
julia> r = 1:4
1:4
julia> r[3]
3
julia> A = rand(0:2, 3, 4)
3×4 Array{Int64,2}:
0 1 2 2
1 1 1 2
1 0 2 1
julia> A * r
3-element Array{Int64,1}:
16
14
11
I think I was looking for
collect(1:n)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With