How do I access / read the attributes of an instance of a class in octave?

To create a class like this in the example , I attached arguments to an instance of the class like so:

function t = train (m, F_z, F_b, varargin)
  ...
  t.m =     m;      % total mass of train [kg]
  t.F_z =  F_z;     % ...
  ...
  t = class (t, "train");

      

Getting field names works

>> t1 = train(100, 150000, 200000);
...
>> fieldnames(t1)
ans =
{
  [1,1] = m
  [2,1] = F_z
  ...

      

But how do I access them? Apparently this is not

>> t1.m
error: invalid index for class
>> getfield(t1, 'm')
error: invalid index for class
error: called from
...

      

If I leave the line t = class (t, 'train');

at the end function t = train (m...

in @train/train.m

, it all seems to work fine ... But then its a struct

, notclass

+3


source to share


2 answers


You can do this in two ways. You can define a way to get it (easy) or customize subsref

(index) (hard).

To define a method, just create @train/m.m

with:

function r = m ()
  r = t.m;
endfunction

      

To set up a subscription, create @train/subsref.m

with:

function r = subsref (val, idx)
  if (strcmp (idx.type, ".") && strcmp (idx.subs, "m"))
    r = val.m;
  endif
endfunction

      

This will only allow you to access the field m

. To provide access to any of the properties of your class, you can simply:



function r = subsref (val, idx)
  r = subsref (struct (val), idx);
endfunction

      

To allow access to a subset of properties, you can:

function r = subsref (val, idx)
  if (strcmp (idx.type, ".") && any (strcmp (idx.subs, {"m", "f2", "F_z"})))
    r = val.(idx.subs{1});
  endif
endfunction

      

But it subsref

controls all indexing, not just when accessing it as a structure. You can let people index the object (perhaps you have a class of carriages and train indexing returns them). The function looks a little strange when run (just like subsasgn

(subscript)), but can be quite useful. You can do:

function r = subsref (val, idx)
  if (strcmp (idx.type, ".") && strcmp (idx.subs, "m"))
    r = val.m;
  elseif (strcmp (idx.type, "()"))
    r = val.wagons(idx.subs{:});
  endif
endfunction

      

+2


source


One quick and dirty way is to violate the OOP philosophy in the octave. There is no need to define methods subsref

or getter

. To access the fields, just convert the object to struct

as



>> t1 = train(100, 150000, 200000);
>> t1_easy = struct(t1);
>> t1_easy.m
>> t1_easy.F_z

      

+2


source







All Articles