Effacer les filtres
Effacer les filtres

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

3 vues (au cours des 30 derniers jours)
fa wu
fa wu le 24 Sep 2023
Modifié(e) : Matt J le 24 Sep 2023
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.

Réponses (1)

Matt J
Matt J le 24 Sep 2023
Modifié(e) : Matt J le 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.

Catégories

En savoir plus sur Construct and Work with Object Arrays dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by