6 ms·
For "2D indexing" into a 1D array it's actually a little awkward. With an n×m matrix, - zero-indexed: i×m+j - one-indexed: (i-1)×m+j OTOH one-based is slight
by repsilat 8y ago
For "2D indexing" into a 1D array it's actually a little awkward. With an n×m matrix,
- zero-indexed: i×m+j
- one-indexed: (i-1)×m+j
OTOH one-based is slightly better for trees stored in 1D arrays:
- zero-indexed: parent=(child-1)/2; children=2×parent+(1, 2).
- one-indexed: parent=child/2; children=2×parent+(0, 1).
My favourite fact about this stuff: in VB (or was it VBA?) when you asked for an array of size n, you actually got an array of size n+1. So people could do 0-based or 1-based indexing and be none the wiser...
- ska 8y agoAll fair enough but not particularly relevant here (in the context of "why Swift"). For doing numeric work in a language actually defined for that purpose, you will have proper 2D (and hopefully n-D) arrays, and hopefully slicing operations on them. So you'll never do this. In this context doing 2D indexing in 1D arrays is a code smell. It does come up in the case of writing libraries for general purpose language with poor support for numerics and linear algebra, but then you should be abstracting this away from your callers.
- overgard 8y agoWell, the nice thing about doing 2d indexing in 1d arrays is the 1d array sits in one contiguous block of memory, which can be important for performance, and also makes it a lot easier to pass the array to C libraries (which I think you alluded to). Whereas in a lot of languages, int[3][3] might be stored as 3 pointers to 3 arrays. I imagine Julia optimizes this?
- improbable22 8y agoYes, in julia A = rand(2,2) is a matrix, and reshape(A,:) is a vector view of the same continuous block of memory. You may also index A[i] directly, as if it were a vector; eachindex(A) is an iterator which uses whichever style of indexing is going to be quickest (and in cache-friendly order).
- ufo 8y agoMany of the low level libraries for numerical computation are coded in Fortran, which is 1-based. So it is a wash in this aspect.
- ska 8y agoThat is one of the things I meant by “proper”, meaning an efficient layout and alignment.
- ryanmonroe 8y agoForgive my ignorance, but are you saying you use A[(i-1)×m+j] to get the element in the i-th row and j-th column? Why not use A[i, j]?
- ddebernardy 8y agoGP wrote (emphasis mine) 'For "2D indexing" into a 1D array'. I presume it's some graphics-related optimization or some pointer arithmetics-related work, but I'd also be curious about some concrete use-cases too.
- newen 8y agoJulia n-D arrays are stored contiguously in memory. So, you can access the memory by reshaping the array into whatever dimension you want and then access it using the A[i,j,k] syntax.