Resizing array of handle objects

16 ビュー (過去 30 日間)
Luca Ferroglio
Luca Ferroglio 2022 年 12 月 19 日
回答済み: Rik 2022 年 12 月 19 日
Hi all,
I'm trying to define a handle object, which is (potentially) an array of objects, and I'm trying to define a method to successfully resize it.
classdef anArrayObject < handle
properties (Access = public)
prop = 0 % just a dummy property
end
methods
% this initializes my array of handle objects
function obj = anArrayObject(n)
if nargin ~= 0
validateattributes(n, {'numeric'}, {'scalar', 'integer' 'positive'});
for i = 1:n
obj(i).prop = i; % Expands the object to become an array of the size n
end
end
end
% Here I'd like to resize my array on demand, but this does not work.
% Any way to resize this array?
function obj = resizeMe(obj, m)
validateattributes(m, {'numeric'}, {'scalar', 'integer' , 'positive'});
if m < numel(obj)
obj = obj(1:m);
end
end
end
end
As from comments in the code: I can successfully crate the array of objects, but the resizeMe function does not do what I want.
myObjArray = anArrayObject(5);
numel(myObjArray)
ans = 5
myObjArray.resizeMe(3);
numel(myObjArray)
ans = 5
Any way to resize this handle object?

回答 (1 件)

Rik
Rik 2022 年 12 月 19 日
The problem is that while your object array is an array of handles, it isn't a handle variable itself. What that means is that you have an array of 5 handle objects, which you then shorten to 3:
myObjArray = anArrayObject(5)
myObjArray =
1×5 anArrayObject array with properties: prop
myObjArray.resizeMe(3)
ans =
1×3 anArrayObject array with properties: prop
Notice with the last result that the initial variable is not actually modified.
The solution I can think of would be to store the array inside the object, instead of exposing it as a normal array. You can probably overlead subsref to get most of the behavior of an array.

カテゴリ

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

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by