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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With