Lemonbonbon
Lemonbonbon

Reputation: 738

Get pointer of class object

I have an object apple created by my own class in MATLAB:

apple = classA();

The class looks like this:

classdef classA < handle

   properties
       color = 'red';
   end

   methods
      function obj = classA()
          % ...
      end
   end
end

The question: How do I get the object or handle pointer of apple? I want to search for objects by their properties, like:

isprop(eval(mat(i).name),'color')

with mat = whos. So I need to get the pointer of the object, represented by the struct mat(i).name. I just need the reference, not a copy of the desired object. The purpose is this:

If I get the pointer somehow, like

ptr_to_apple_object = get_pointer_fct( mat(i).name )

then I am able to change the properties of the apple-object like:

ptr_to_apple_object. color = 'yellow'

Do you have any ideas? Thanks.

Upvotes: 2

Views: 547

Answers (1)

Suever
Suever

Reputation: 65430

There's really no good way to find all current objects of a particular class, but you could use whos to get a struct about all variables, loop through this and determine which ones have the property you and then modify

variables = whos;

for k = 1:numel(variables)
    obj = eval(variables(k).name);

    if isobject(obj) && isprop(obj, 'color')
        obj.color = 'yellow'; 
    end
end

If you're looking for a specific class, you can use the class field of the output of whos

is_class = ismember({variables.class}, 'classA');
instances = variables(is_class);

for k = 1:numel(instances)
    obj = eval(instances(k).name);
    obj.color = 'yellow';
end

Update

Since you are subclassing handle, when you assign your instance to a new variable (obj = val(variables(k).name) above), it does not create a copy of your instance, but rather a new reference to the same object.

b = classA;
c = b;

b.color = 'red';

c.color
%   'red'  

Upvotes: 3

Related Questions