Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a 1-based array to a 0-based array in Julia

Tags:

julia

I'm writing some numerical code in which it would be more convenient to use 0-based indexing than Julia's default 1-based indexing. Julia does support 0-based indexing, but the documentation for it is aimed squarely at developers, so I'm a bit confused about how to use it.

Specifically: if I call rand(10,10) I get a 10x10 array with indexes from 1 to 10. Is there a simple equivalent command that will return an array with indexes from 0 to 9 instead? Or alternatively, can I easily convert this to a 0-based array instead of a 1-based one?

like image 329
N. Virgo Avatar asked Jun 06 '19 11:06

N. Virgo


People also ask

How do you make an array of zeros in Julia?

This is usually called with the syntax Type[] . Element values can be specified using Type[a,b,c,...] . zeros([T=Float64,] dims::Tuple) zeros([T=Float64,] dims...) Create an Array , with element type T , of all zeros with size specified by dims .

Why do Julia arrays start at 1?

Arrays should start at 1 because as people count starting from one. The thing with 0-based indexing is that you always then have to write code of the type for i=0:len(a)-1 when iterating.

Is Julia 1 or 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.

Is Julia 0-based?

Julia, unlike the majority of the languages, is 1-based instead of 0-based. This means that arrays start at index 1. This causes significantly different algorithms and loop designs. To see the merits of each system and some use cases, refer to this document: Indexing of Arrays: 0 vs 1.


1 Answers

I'm posting a self-answer because the question was answered by Bogumił Kamiński in the comments.

There is some user-level documentation here, though at the time of writing it is rather short and consists entirely of examples, so one has to infer the intended semantics and guess at best practices.

However, it seems the command

OffsetArray(rand(10,10),0:9,0:9)

achieves what I was asking for, and Bogumił Kamiński confirmed that this is the correct way to do it, so one can guess that this doesn't needlessly copy the array, etc.

One hopes that some proper documentation will be written at some point, since this is quite an important feature. (One hopes this for many important features of Julia.)

like image 152
N. Virgo Avatar answered Oct 10 '22 07:10

N. Virgo