Memory preallocation for array of objects with irregular array length property

조회 수: 3 (최근 30일)
Stergios
Stergios 2023년 8월 30일
댓글: Stergios 2023년 8월 31일
Hi,
I have an array of objects from a class (let's say MyClass) and each object has as property an array of different length for each object. For example: MyClass_object(1).MyArray is 100x1 and MyClass_object(2).MyArray is 200x1.
Code for my class:
classdef MyClass < handle
properties
MyArray
end
methods
function obj = MyClass(array_length)
obj.MyArray = zeros(array_length,1);
end
end
end
Memory preallocation:
lengths = [100;200]
MyClass_object(1,:) = MyClass(lengths(1));
MyClass_object(2,:) = MyClass(lengths(2));
My question is: how is it possible to preallocate memory both for the objects and the arrays without coding one by one?
I tried this:
lengths = [100;200];
for i=1:length(lengths)
MyClass_object(i,:) = MyClass(lengths(i));
end
But then I get an warning: Variable appears to change in size in every loop iteration.
Note: vector "lengths" might have 50 or more values.
Thanks!
  댓글 수: 2
James Tursa
James Tursa 2023년 8월 30일
Please show a small example class and explain what problems you are having with setting properties of different objects to different sizes.

댓글을 달려면 로그인하십시오.

답변 (1개)

Walter Roberson
Walter Roberson 2023년 8월 31일
Provided that MyClass_Object does not already exist:
lengths = [100;200];
NumL = length(lengths);
MyClass_Object(NumL, :) = MyClass(lengths(end));
for i=1:NumL-1
MyClass_object(i,:) = MyClass(lengths(i));
end
  댓글 수: 1
Stergios
Stergios 2023년 8월 31일
Hi Walter
Most probably you mean this:
MyClass_object(1:NumL, :) = MyClass(lengths(end));
instead of
MyClass_Object(NumL, :) = MyClass(lengths(end));
right?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by