Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of firstindex in Julia?

Tags:

julia

From documentation it says firstindex() finds the first index of a collection. Why not just use 1? What could be the case when it's not 1?

like image 517
Alex Craft Avatar asked Feb 27 '20 06:02

Alex Craft


People also ask

Is Julia 0 indexed?

Conventionally, Julia's arrays are indexed starting at 1, whereas some other languages start numbering at 0, and yet others (e.g., Fortran) allow you to specify arbitrary starting indices.

How do you set an index in Julia?

Set elements at a given index of array in Julia – setindex!() Method. The setindex!() is an inbuilt function in julia which is used to store values from the given array X within some subset of A as specified by inds.


2 Answers

The first index is not necessarily 1 because Julia supports custom indexing. To understand why it is useful, you can't beat Tim Holy's blog post.

Custom indices allow you to encode information about your data in the indexing pattern itself: sometimes it is more natural to start counting from one, sometimes from zero, sometimes from some more arbitrary number.

Other times, such as when you are writing generic algorithms, you do not really care about the specific index. In which case you can use abstractions such as firstindex, lastindex, and eachindex.

Most often, it is better to avoid referring to an index altogether and just iterate over a collection's elements (e.g. for x in xs).

Julia allows you to use the most effective strategy for your data.

like image 128
David Varela Avatar answered Oct 22 '22 16:10

David Varela


There are special array types like for example OffsetArrays.jl which can have arbitrary indices.

like image 16
carstenbauer Avatar answered Oct 22 '22 14:10

carstenbauer