Can object properties be assigned in bulk without the need for a loop statement?

1 visualizzazione (ultimi 30 giorni)
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.

Risposte (1)

Matt J
Matt J il 24 Set 2023
Modificato: Matt J il 24 Set 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.

Categorie

Scopri di più su Construct and Work with Object Arrays in Help Center e File Exchange

Prodotti


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by