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?
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.
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.
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.
There are special array types like for example OffsetArrays.jl which can have arbitrary indices.
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