danatron
danatron

Reputation: 717

How to save MATLAB classes to file

I would like to load and save some objects instantiated from a classdef style class. I can use "save" and "load" when the objects exist in the workspace, but not outside.

For example, if I have a class called manager, that needs to load and save different employee classes, the employee classes will not exist in the workspace.

Do I need to write a custom save routine? Is there a way of leveraging the existing tools?

Upvotes: 2

Views: 2936

Answers (1)

Andrey Rubshtein
Andrey Rubshtein

Reputation: 20915

First of all, I hope I understand your question correctly.

You have something like this:

   class Manager
      properties
          Employees
      end
   end

   class Employee

   end

You have an instance of Manager

   manager = Manager();
   e1 = Employee();
   e2 = Employee();;
   manager.Employees{1} = e1;
   manager.Employees{2} = e2;

And you want to save it.

In this case, even if you don't have e1 and e2 in your workspace, save command will save them while saving Manager.

However, in order to load them correctly, you must have both Employee and Manager in your working directory. That makes sense, because there is no other way knowing what kind of class it was. In fact, you will get an error:

Warning: Variable 'manager' originally saved as a Manager cannot be instantiated as an object and will be read in as a uint32. 
Warning: Variable 'e1' originally saved as a Employee cannot be instantiated as an object and will be read in as a uint32. 
Warning: Variable 'e2' originally saved as a Employee cannot be instantiated as an object and will be read in as a uint32. 

Upvotes: 1

Related Questions