how to preallocate an object array?

22 ビュー (過去 30 日間)
Mark Ricard
Mark Ricard 2020 年 11 月 17 日
コメント済み: Walter Roberson 2020 年 11 月 18 日
I am trying to preallocate an object array of a class. Below is the class that I am using in MyobjectArray class
classdef MyData
properties
x = []; % a column vector of data
end
methods
function obj = MyData(nRows)
if nRows > 0
obj.x = zeros(nRows,1);
end
end
end
end
In the code below I am using obj.value = zeros(nArrays,1); to preallocate. What is the correct way to preallocate an object array?
classdef MyobjectArray
properties
value = []; % an array of MyData objects
end
methods
function obj = MyobjectArray(nArrays, nRows)
if nargin ~= 0
obj.value = zeros(nArrays,1);
for i = 1:nArrays
obj(i).value = MyData(nRows);
end
end
end
end
end

採用された回答

Walter Roberson
Walter Roberson 2020 年 11 月 17 日
Do not initialize value to [] if the property is not going to have type "double" .
If it is going to have type that is one of the built-in types, use empty() to create an empty array of the correct type
If MyData is not going to return double, then do not assign zeros to initialize the property . If MyData(nRows) returns a constant value you would be better with
[obj(1:nArrays).value] = MyData(nRows);
  2 件のコメント
Mark Ricard
Mark Ricard 2020 年 11 月 18 日
編集済み: Walter Roberson 2020 年 11 月 18 日
This runs but I am not correctly prellocating the array of MyData objects.
The goal is to create 3 arrays of MyData objects, each MyData object is a column vector
of 10 doubles.
classdef MyobjectArray
properties
value; % an array of MyData objects
end
methods
function obj = MyobjectArray(nArrays, nRows)
if nargin ~= 0
for i = 1:nArrays
obj(i).value = MyData(nRows);
end
end
end
end
end
classdef MyData
properties
x = []; % a column vector of data
end
methods
function obj = MyData(nRows)
if nRows > 0
obj.x = linspace(1,nRows,nRows)';
end
end
end
end
Walter Roberson
Walter Roberson 2020 年 11 月 18 日
function obj = MyobjectArray(nArrays, nRows)
if nargin ~= 0
[obj(1:nArrays).value] = deal(MyData(nRows));
end
end
Tested.
This does assume that myData(nRows) returns constant output.
The property will be set to a vector in which each item has the same data pointer -- one original copy of the MyData object being pointed to multiple times. However, as these are value class objects and not handle class objects, that is not a problem unless you plan to use mex functions that overwrite the input without properly checking first to see if they are dealing with shared copies or not: any conformant function will either automatically or deliberately use copy-on-write.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCell Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by