Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get a list of numbers from 1 to n in Julia?

Tags:

range

julia

In MATLAB you could write 1:n. Is there something similar to this notation in Julia?

like image 648
notabot Avatar asked Oct 06 '19 22:10

notabot


2 Answers

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
like image 64
mbauman Avatar answered Dec 10 '22 03:12

mbauman


I think I was looking for

collect(1:n)
like image 43
notabot Avatar answered Dec 10 '22 03:12

notabot