Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save variables to file at runtime

I'm looking for some functionality in Julia comparable to Matlab's

save('myfile.mat', 'myvar1', 'myvar2')

For example, using HDF5.jl, it is easy to do

@write filename myvar1 myvar2

But this requires that I know exactly which variables I want to write to the file.

I'd like to be able to choose which variables to write at run time, in a function scope, and specify their names using symbols or strings.

vars = [:myvar1, :myvar2]
@write filename vars

What would be the best way to accomplish this?

EDIT

I know that I can use save from JLD.jl as save("file.jld", "myvar1", myvar1). But I want to be able to save a list of variables that are not known at compile time, allowing a single call to save (or similar):

if condition
    myvar1 = 1
    vars = [:myvar1]
else
    myvar1 = 1
    myvar2 = 2
    vars = [:myvar1, :myvar2]
end

# what goes here?
save(filename, vars...)
like image 300
Micah Smith Avatar asked Dec 06 '25 07:12

Micah Smith


2 Answers

You may want to take a look at the JLD package, which builds on HDF5 with better support of user-defined Julia types. Both HDF5 and JLD provide functions for save that take run-time names for variables.

like image 158
StefanKarpinski Avatar answered Dec 09 '25 15:12

StefanKarpinski


You can use serialize and deserialize:

vars = Dict()
if condition
   myvar = 1
   vars[:myvar1] = myvar1
else
   myvar1 = 1
   myvar2 = 2
   vars[:myvar1] = myvar1
   vars[:myvar2] = myvar2
end

f = open( filename, "w" )
serialize( f, vars )
close( f )

to read:

f = open( filename, "r" )
vars = deserialize( f )
close( f )

if you don't need to save variable names you can use array instead of dict: vars = []

like image 31
krychu Avatar answered Dec 09 '25 16:12

krychu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!