Home > Back-end >  MATLAB dynamically read/write attributes - getattr, setattr?
MATLAB dynamically read/write attributes - getattr, setattr?

Time:08-28

class A(): pass
a = A()
setattr(a, 'dog', True)

Is there a MATLAB equivalent? If not, what's the most compact alternative? Currently I do

for i=1:length(keys)
    k = keys{i};
    v = values{i};
    if k == "arg1"
        obj.arg1 = v;
    elseif k == "arg2"
        obj.arg2 = v;
    ...

Likewise for getattr? If needed, assume all keys are already Properties.

Non-Python readers: setattr(obj, 'a', 1) <=> obj.a = 1 and getattr(obj, 'a') <=> obj.a.

CodePudding user response:

obj.arg1 is the same as obj.('arg1').

So in your code snippet is equivalent to:

for i=1:length(keys)
   obj.(keys{i}) = values{i};
end
  • Related