Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of pointers to objects in Matlab?

Tags:

I'm writing a Matlab script where I have a bunch of objects of a same self defined class, say A, B and C. Then I have a function that work on any of the 2 objects, like func(A,B).

Now I want to pick an object, say A, and then func(A,x) through all the other objects. So basically achieve something like:

func(A,B)
func(A,C)
A.update()

func(B,A)
func(B,C)
B.update()

...

So I need to create an array of all the objects I can loop through, while excluding itself of course. I tried to do it with cell array, so I have:

AllObjs = {A,B,C}
for i=1:length(AllObjs)
  if ~isequal(A, AllObjs{i})
    func(A, AllObjs{i})
  end
end
A.update()

However, when A is updated, the A in AllObjs doesn't get updates. So for the next loop I have to create a new array of all the objects. It's doable in this simple example but not manageable when the objects get updated elsewhere. So I would like to have an array of pointers to all the objects. My Google search tells me there's no pointer in Matlab, but is there a way to achieve what I want to do here?

like image 646
LWZ Avatar asked Sep 15 '17 18:09

LWZ


1 Answers

I suspect (its difficult without seeing your code) your classes A, B & C do not inherit from from handle.

Take the examples below:

classdef noHandle
  properties
    name = '';
  end
  methods
    function obj = noHandle ( name )
      obj.name = name;
    end
  end
end

A = noHandle ( 'A' );
B = noHandle ( 'B' );
C = noHandle ( 'C' );
allObjs = { A B C }
allObjs{1}.name   % check its name is "A"
% change the name of A
A.name = 'AAA'
allObjs{1}.name   % see that allObjs{1} is still A.

However if you do:

classdef fromHandle < handle
  properties
    name = '';
  end
  methods
    function obj = fromHandle ( name )
      obj.name = name;
    end
  end
end

Then do:

A = fromHandle ( 'A' );
B = fromHandle ( 'B' );
C = fromHandle ( 'C' );
allObjs = { A B C }
allObjs{1}.name   % check its name is "A"
% change the name of A
A.name = 'AAA'
allObjs{1}.name   % see that allObjs{1} is updated to AAA.
like image 170
matlabgui Avatar answered Oct 04 '22 15:10

matlabgui