Passing an array to a function for use as dims in Array{}

Starting a new session solved the issue
TIL: If it really seems like it should work, give it a try in a new session.

Original post:
I got help on reading binary data (thanks!), but stumbled into a secondary problem.

Using julia 1.1.1    1.0.4
Please note: code examples are copied by hand. I can’t have web access and julia one the same machine. Mistakes are possible.

 function read_dat(filename, dims, T)
  img = Array{T}(undef, (dims)) 
  do io 
    read!(io, img) 
#Calling it with this works fine:
data = read_dat("myfilename.img", (251, 260), Float32)
# But trying to use variables for dims does not:
bands=250; lines=260; samples=440;
fn = “myfile.img”;
dtype = Float32;
data = read_dat(fn, (bands,lines,samples), dtype)

fn and dtype pass ok, as does just a single variable for dims, but trying to pass all 3 for dims results in
no method matching Array{Float32,N} where N(::UndefInitializer, :: Tuple{String,String,String})
I don’t understand the error message and didn’t find anything in the docs to decode it.

In use, dims could be 1,2, or 3 values.

Hm, is this the exact code you’re running? The error message points to your Array constructor (the first line in the function), but just doing this:

function read_dat(filename, dims, T)
    img = Array{T}(undef, dims) 

read_dat("myfilename.img", (251, 260), Float32) # returns 250x260 Array{Float32, 2}

bands=250; lines=260; samples=440;
fn = "myfile.img";
dtype = Float32;
read_dat(fn, (bands,lines,samples), dtype) # returns 250x260x440 Array{Float32, 3}

works for me as expected. Which Julia version are you using?

hmmm… i typed in your shortened version but still get the same error when trying to use variables for dims.

This is the output from a fresh REPL session in Julia 1.2.0:

julia> function read_dat(filename, dims, T)
           img = Array{T}(undef, dims)
read_dat (generic function with 1 method)

julia> read_dat("myfilename.img", (251, 260), Float32) 
251×260 Array{Float32,2}:

julia> bands=250; lines=260; samples=440;

julia> fn = "myfile.img";

julia> dtype = Float32;

julia> read_dat(fn, (bands,lines,samples), dtype)
250×260×440 Array{Float32,3}:

Can you provide the full output (minus all the printed empty arrays) from running the above in a fresh session on your machine?

1 Like

Oof! So in a fresh session I get exactly what you get. Everything is ok.
I don’t understand why a new session would make a difference, but thank you so much.
I feel a bit silly, but at least I’ve learned something new to try in the future. :slight_smile:

This is quite hard to say in hindsight, but there’s alsway a slim chance that by accident you redefined some function by using a funny variable name, so trying in a fresh session often helps - glad it works now!