Binary_reading

Hello!
I need help with the function for reading the binary file. I’m using

function read_bin(filename, dims::N) where N<:Integer
    stream = open(filename, "r");
    data = read(stream, Float16, dims);
    close(stream);
    return data
end

but this is giving error that I can not solve. Can someone help me?

There are couple options, I think the most straight forward one is this:

function read_bin(filename, dims::N) where N<:Integer
    # initial an array with known size
    data = Vector{Float16}(undef,dims)
    # or data = zeros(Float16,10)
    stream = open(filename, "r");
    # read stream into the pre-allocated typed-vector
    read!(stream, data);
    close(stream);
    return data
end

It looks like you are new to Julia, Welcome, you can ask this is kinda general question in First Step https://discourse.julialang.org/c/user/first-steps. You will get lots of help from there.

Even more compactly:

read_bin(filename, dims) = read!(filename, Vector{Float16}(undef, dims))

Argument-type declarations aren’t necessary, but if you want them for clarity I would suggest read_bin(filename::AbstractString, dims::Integer) (no where clause` is needed).

Note that the above code is endian-dependent; you could use ntoh or similar on the result to convert endianness if needed, or use a portable file format like HDF5.

3 Likes

Thanks!.
Yes, i’m new in julia.

I have another problem. I’m trying use the function ecdf for an array 2-D, but is giving this error:
" MethodError: no method matching ecdf(::Array{Float16,2})
Closest candidates are:
ecdf(!Matched::AbstractArray{T<:Real,1}) where T<:Real at /home/user/.julia/packages/StatsBase/rTkaz/src/empirical.jl:50"

This is a line that gives error, where matR is 2D array.
“mX = reshape(ecdf(matR)(matR), (lin, col))”

ecdf doesn’t work on arrays of rank > 1, presumably because it doesn’t want to assume which ordering you intend. One way to flatten the array so that ecdf accepts it is

ecdf(vec(A))

for some array A. Note that this will give you column-wise (first index first) ordering because this is Julia’s memory layout. You can also use reshape. Note also that you can get the documentation for functions in the Julia REPL by entering ?functionname.

Thanks!
This is a normal array of data read with line and col. Still is does not work?

You’d need to provide some information about the object you are trying to flatten and what errors you are getting for it to be possible to help you. Please see Please read: make it easier to help you

1 Like

Yes, thanks. I will read.

1 Like