Vectorize class function over all objects

조회 수: 12 (최근 30일)
Marc Laub
Marc Laub 2022년 10월 27일
편집: Varun 2023년 8월 31일
Hey,
I have a handle class and each of those classes has some properties that will be changed over time repeatedly.
classdef precipitates < handle
properties
radius=...;
compositions
end
function [radius]=growth(radius,composition)
...
end
end
the Growth funtion can be easily vectorized, but within the class, radius and composition is jst a scalar. So when i would cll this cunction for all objects, I would loop over them.
Is there a way tht the growth function is applied to all objects, where the input radius and composition is the vector of radius and composition from all objects?
The only other way would be to extract radius ad composition from all objects, apply the function externaly and then overwrite the properties...but that would make the class kind of unnecessary when I just use it as well arranged structure to store data...
Best regards

답변 (1개)

Varun
Varun 2023년 8월 31일
편집: Varun 2023년 8월 31일
Hi Marc,
I understand that you want to implement “growth” function/ method in a class which can modify properties like “radius” and “composition” of multiple objects at a time.
So, first you have to declare this function “growth” as “Static”, then pass an input parameter “objArray” (array of objects) and then update the fields of multiple objects in vectorized manner as shown below. Please refer the following updated code:
classdef precipitates<handle
properties
radius
compositions
end
methods (Static)
function newRadius = growth(objArray, radiusVec, compositionVec)
newRadius = radiusVec+compositionVec;
x=num2cell(newRadius);
[objArray.radius]=deal(x{:});
end
end
end
And you can use this function as below:
>> objArray = [precipitates(), precipitates(), precipitates()] % Create an array of precipitates objects
>> radius=[1 2 3];
>> composition=[4 5 6];
>> newRadius = precipitates.growth(objArray,radius,composition)
>> objArray.radius %updated radius of all objects.

카테고리

Help CenterFile Exchange에서 Weather and Atmospheric Science에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by