Search code examples
matlabclassimportloadinstance

Load or import map for use by class instance in matlab


I have a containers.Map file/variable that I've defined through the Matlab Command Window (or some other script) and have saved it to directory. I'd like to be able to have an instance of my class be able to use that map without having to define it in the class definition, or with some other function that defines it each time the function is called. So I have:

myMap.mat

and in a separate myClass.m file (in the same directory) i'd like to be able to call myMap like so:

classdef myClass < handle
    properties
        number
    end
    methods
        function obj = myClass(input)
            obj.number = myMap(input);
        end
    end
end

What's the most efficient way to get myMap "into the class" so that the instance can use it? matfile has been giving me some Warnings about format not supporting partial loading, and I can't imagine load is terribly efficient. Any suggestions is appreciated.


Solution

  • There are many approaches you can use but, honestly, I think the simplest one would be using a persistent object in your class constructor, as follows:

    classdef myClass < handle
        properties
            number
        end
    
        methods
            function obj = myClass(input)
                persistent pmap;
    
                if (isempty(pmap))
                    load('map.mat','map');
                    pmap = map;
                end
    
                obj.number = pmap(input);
            end
        end
    end