Vladislav
Vladislav

Reputation: 3

Loading MATLAB object from a file

In MATLAB I am loading my custom class object from a file. It contains references to other files that should be located on the drive next to the object file. Is there a way to get the location of the file from which the object is loaded during the initialization?

Example:

Thanks!

Upvotes: 0

Views: 191

Answers (1)

Wolfie
Wolfie

Reputation: 30047

You could create a custom load function, i.e.

function obj = loadMyObj( filepath )
    data = load( filepath );
    obj = data.obj; % load returns the object "obj" in a struct
    obj.filepath = filepath;
end

Then use loadMyObj instead of load.

Of course this requires your object to have the filepath property, but that's a given if you want it to retain the location it was loaded from.

Another alternative could be to but this behaviour into the class constructor for your object, then call something like

obj = myClass( 'C:\some\path\file.mat' );

Where the constructor loads the file, assigns the properties stored in the file, and stores the path too.

Upvotes: 1

Related Questions