ItsMe
ItsMe

Reputation: 23

MATLAB - array of objects is empty after exiting function

classdef ObjData < matlab.mixin.Copyable
  properties
    id;
  end

  methods

    function obj = ObjData(path)           
        [~,name] = fileparts(path);
        obj.id = name;
    end
  end
end

classdef StudyData
  properties
    objs = []
  end

  methods
    function obj = StudyData()
        obj.itarate_study_folder();
    end   
  end

  methods (Access = private)     
    function obj = itarate_study_folder(obj)
        flist = findfiles('*.obj',obj.path);
        if isempty((flist)) == 0
            for k=1:length(flist)
                 if ~isempty(obj.objs)
                    obj.objs(end+1) = ObjData(flist{k});
                 else
                    obj.objs = ObjData(flist{k});
                 end
            end
        end
    end
  end
end

In this code I try to populate the StudyData.objs array with elements of type ObjData.
I try to to so in StudyData.itarate_study_folder() function.

The issue is that as long a I'm in the scope of itarate_study_folder(), the array looks ok, but when exiting this function, the array is empty again.

I also tried to pre-allocate the array before entering itarate_study_folder() with empty objects, but it didn't help.

Could you help me figuring out what am I missing?

Upvotes: 1

Views: 100

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60574

You define the function as

function obj = itarate_study_folder(obj)

So when you call the function, you need to collect the output argument:

obj = obj.itarate_study_folder();

In MATLAB, all arguments are passed by value by default. obj.itarate_study_folder() is the same as itarate_study_folder(obj), the object is passed by value, not by reference. This means that the function has a copy of that object.


If you want the syntax

obj.itarate_study_folder();

to modify the object, then the object has to be a handle. To make it so, convert your class into a handle class by inheriting from handle:

classdef StudyData < handle

For handle classes, the function should not return the object:

function itarate_study_folder(obj)

However, handle classes should only be used for classes that manage some resource, like a graphical display or a file. Such objects can in general not be copied, as multiple copies would free the resource multiple times.

For objects that only store data, use a non-handle class. Your ObjData class, by inheriting from matlab.mixin.Copyable, is a handle class. It doesn’t seem to manage storage, so it would be better if this were a plain class.

Note that MATLAB uses lazy copying, which is a different approach to efficiency than passing data by reference. Don’t use handle classes if you think using them will speed up code by avoiding copies, it won’t.

Upvotes: 1

Related Questions