Search code examples
matlabdictionarystructjulia

How to create a struct or type from a dictionary in Julia?


I have imported a bunch of data from a .mat file (MATLAB format) and they come as dictionarys, but it's kind of anoying using them, so I wanted to pass it for a struct. I know I can do this:

using MAT

struct model
    trans
    means
    vars
end

vars = matread("data.mat")
hmm1=model(vars["hmm1"]["trans"],vars["hmm1"]["means"],vars["hmm1"]["vars"])

Is there a way to do this without typing every key of the dictionay?


Solution

  • There's probably no way to avoid directly accessing the relevant keys of your dictionary. However, you can simplify your life a little by making a custom Model constructor that takes in a Dict:

    using MAT
    
    struct Model
        trans
        means
        vars
    end
    
    function Model(d::Dict)
        h = d["hmm1"]
        Model(h["trans"], h["means"], h["vars"])
    end
    
    d = matread("data.mat")
    
    Model(d)