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

1 回表示 (過去 30 日間)
fa wu
fa wu 2023 年 9 月 24 日
編集済み: Matt J 2023 年 9 月 24 日
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 Center および File ExchangeConstruct 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