Julia: collecting n-dimensional generators

Created on 17 May 2016  路  6Comments  路  Source: JuliaLang/julia

Hi,
while playing with nd generators I have found what I think to be an inconsistency. Here is a demo:

julia> f = (i for i=1:2, j=1:2);

julia> collect(f)
2脳2 Array{Int64,2}:
 1  1
 2  2

I would expect to see:

2脳2 Array{Int64,2}:
 1  2
 1  2

because I am expecting j to vary the fastest, and elements to be collected column-wise.

Currently on:

julia> versioninfo()
Julia Version 0.5.0-dev+4112
Commit 97dc858* (2016-05-16 15:27 UTC)
Platform Info:
  System: Darwin (x86_64-apple-darwin15.4.0)
  CPU: Intel(R) Core(TM) i7-4980HQ CPU @ 2.80GHz
  WORD_SIZE: 64
  BLAS: libopenblas (USE64BITINT DYNAMIC_ARCH NO_AFFINITY Haswell)
  LAPACK: libopenblas64_
  LIBM: libopenlibm
  LLVM: libLLVM-3.7.1 (ORCJIT, haswell)

Most helpful comment

It's a somewhat unfortunate situation, but it's one we're stuck with without rewriting all math books.

All 6 comments

Matrices are indexed by row then column, so the other way would not match the way you index.

AHH, I see the point. That is because I thought collect(f) was somewhat equivalent to

a = []
for i = 1:2, j=1:2
    push!(a, i)
end
reshape(a, 2, 2)

which gives

2脳2 Array{Int,2}:
 1  2
 1  2

Thanks

It's a somewhat unfortunate situation, but it's one we're stuck with without rewriting all math books.

The point is to look at it as a 2d array comprehension

f = [i for i =1:2, j=1:2]

in which the indexing behaviour is clear. Then, the meaning of

g = (i for i =1:2, j=1:2)

is immediately apparent.

The order discrepancy between [i for i=1:2, j=1:2] and for j=1:2, i=1:2; i; end is indeed a little jarring at first. Someone once pointed out that the iteration variable that's "closest" to the code moves fastest, which is a very nice way to think about it.

That is what I initially thought. However, in the above case one could say that i is closest to for i =1:2 馃槃

Was this page helpful?
0 / 5 - 0 ratings