Extract property from all instances of the same class in Matlab, write value to file

I would like to automatically get certain properties from all instances of the same class in my workspace.

Example: I have a class C1, with instances a, b, c, d. Each of them has a specific property called x. I would like to get all x. How should I do it?

+4
source share
1 answer

Here is one opportunity. Let's say that I want to find all the doubles in the workspace. I could do something like this

>> x = 12.3; >> y = 45.6; >> z = '789'; 

Get a list of all variables in the workspace

 >> vars = whos(); 

Find out which ones double

 >> location = strcmp('double',{vars.class}); 

Get names

 >> names = {vars(location).name}; >> names names = 'x' 'y' 

If you want to get an array of some property x (let's say I want to get the cosine of each double), you can do something like this

 >> N = length(names); >> arr = NaN(1,N); >> for n = 1:N obj = eval(names{n}); # dubious use of 'eval' arr(n) = cos(obj); # assign the relevant property to an array end 

Now you have

 >> arr arr = 0.9647 -0.0469 

Here is an example of using a custom object. Firstly, I put this code in a DProtein.m file

 classdef DProtein properties x; y; end methods function self = DProtein(x, y) self.x = x; self.y = y; end end end 

Now I am creating a couple of objects

 >> a = DProtein(1, 'foo'); # ax = 1 >> b = DProtein(2, 'bar'); # bx = 2 

I find all objects of the correct class in the workspace as before

 >> vars = whos(); >> location = strcmp('DProtein', {vars.class}); >> names = {vars(location).name}; 

Now the loop collects an array of each object

 >> for n = 1:length(names) objects(n) = eval(names{n}); # NB important that 'objects' does not # exist in the workspace before this line! end 

And you can collect all properties like this

 >> [objects.x] ans = 1 2 
+4
source

Source: https://habr.com/ru/post/1494446/


All Articles