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

1 次查看(过去 30 天)
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.

回答(1 个)

Matt J
Matt J 2023-9-24
编辑:Matt J 2023-9-24
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.

类别

Help CenterFile Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by