Can object properties be assigned in bulk without the need for a loop statement?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Please take a look at lines 15 to 17 of the following code, where a loop is used to copy two properties of an object to two properties of another object in bulk. Is there a vectorized approach to achieve this without the need for a loop statement?
classdef Ref < handle
properties
a
b
end
methods
function obj = Ref ()
obj.a=rand(1);
obj.b=rand(1);
end
function newobj=simpleClone(obj) % 简单克隆
newobj = Ref ();
metaobj = metaclass(obj ) ; %得至0 metaobj
props = {metaobj.PropertyList.Name}; %得至G props 名字
for j = 1:length(props) % 遍历
newobj.(props{j}) = obj.(props{j});
end
end
end
end
I've attempted the following methods, but none of them were successful.
obj=Ref();
obj.('a','b') %not work
obj.[a,b] %not work
eval('obj.a','obj.b') %not work
[obj2.a,obj2.b]=deal(obj1.a,obj1.b) %This method works but cannot be combined with the cell array of property names obtained from metaobj.PropertyList.Name.
0 Kommentare
Antworten (1)
Matt J
am 24 Sep. 2023
Bearbeitet: Matt J
am 24 Sep. 2023
Is there a vectorized approach to achieve this without the need for a loop statement?
No, there isn't. Nor is there anything to be gained if there was, except to simplify syntax. There is no memory-contiguity for property data, so vectorization will not help with speed.
For abbreviating syntax, however, you can make your own utility function. Attached is what I use.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Construct and Work with Object Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!