oop - Retrieve property from all instances of one class in Matlab, write value to file -
i automatically retrieve properties instances of same class in workspace.
ex.: have class c1, instances a, b, c, d. each of these have property called x. retrieve x's. how go this?
here's 1 possibility. let's want find doubles in workspace. this
>> x = 12.3; >> y = 45.6; >> z = '789';
get list of variables in workspace
>> vars = whos();
figure out ones doubles
>> location = strcmp('double',{vars.class});
get names
>> names = {vars(location).name}; >> names names = 'x' 'y'
if wanted array of property x (say want cosine of each double) this
>> n = length(names); >> arr = nan(1,n); >> n = 1:n obj = eval(names{n}); # dubious use of 'eval' arr(n) = cos(obj); # assign relevant property array end
now have
>> arr arr = 0.9647 -0.0469
here's example using custom object. first, put code in file dprotein.m
classdef dprotein properties x; y; end methods function self = dprotein(x, y) self.x = x; self.y = y; end end end
now create couple of objects
>> = dprotein(1, 'foo'); # a.x = 1 >> b = dprotein(2, 'bar'); # b.x = 2
i find of objects of correct class in workspace before
>> vars = whos(); >> location = strcmp('dprotein', {vars.class}); >> names = {vars(location).name};
now loop collects array of every object
>> n = 1:length(names) objects(n) = eval(names{n}); # n.b. important 'objects' not # exist in workspace before line! end
and can collect properties this
>> [objects.x] ans = 1 2
Comments
Post a Comment