MAT.jl icon indicating copy to clipboard operation
MAT.jl copied to clipboard

Function handle support

Open matthijscox opened this issue 1 month ago • 4 comments

We don't error anymore on function handles since MAT v0.11, but let's remember to provide good read-write support at some point:

Current behavior:

julia> sin_f = matread("test/v7.3/function_handles.mat")["sin"]
Dict{String, Any} with 4 entries:
  "function_handle" => Dict{String, Any}("function"=>"sin", "file"=>"", "type"=>"simple")
  "sentinel"        => '@'
  "separator"       => '/'
  "matlabroot"      => "/opt/MATLAB/R2018b"

julia> anon = matread("test/v7.3/function_handles.mat")["anonymous"]
Dict{String, Any} with 4 entries:
  "function_handle" => Dict{String, Any}("function"=>"sf%0@(x)x", "workspace"=>MatlabOpaque("any"=>Any[MatlabOpaque(); Dict{String, Any}();;]), "file"=>"", "within_file_path"=>"__base_function", "ty…
  "sentinel"        => '@'
  "separator"       => '/'
  "matlabroot"      => "/opt/MATLAB/R2018b"

When we write these, you get a struct in MATLAB.

matthijscox avatar Dec 03 '25 12:12 matthijscox

I think we can already load function handles already, but as a struct/dict. We could use another wrapper MatlabFunction for this, it's what SciPy (and matio) uses.

I can take this up along with write support.

foreverallama avatar Dec 05 '25 17:12 foreverallama

Can you add the type for MatlabFunction or something like that? The data would be a 1x1 struct in MATLAB or a Dict in Julia. I'm not very familiar with the syntax and don't want to spend too much time on it.

I'll update the read and write methods accordingly

foreverallama avatar Dec 07 '25 08:12 foreverallama

I see. Well we can go easy-mode and make another dict wrapper, like MatlabOpaque:

struct FunctionHandle
    d::Dict{String,Any} # or OrderedDict
end
# add dict-like interface methods for ease of use? 
# do we even need them? or we just write `FunctionHandle.d` as a struct with some extra HDF5 wrapping?

But if the function handle always has these 4 fields, it might be better for code readability to create a special type. Though we'd have to do more research to figure out what the options are per property...

struct FunctionHandle
    function_handle::Dict{String, Any} # or OrderedDict
    sentinel::Char
    separator::Char
    matlabroot::String
end

Is the order of the fields import by the way, for writing? I guess we'd have to find out.

matthijscox avatar Dec 10 '25 08:12 matthijscox

Lets keep it easy. Function handle serialization gets weird when they're nested or a handle to a classdef method

foreverallama avatar Dec 10 '25 17:12 foreverallama