- Create a handle class: Define a custom class that inherits from handle, so objects are modified by reference.
- Store in “containers.Map”: Use a “containers.Map”with integer keys and handle objects as values to store and retrieve objects by unique ID.
- Access via temporary variable: Since “containers.Map” doesn't support chained indexing, first assign the object to a temporary variable before accessing or modifying its properties.
- Changes persist: Because the objects are handles, any changes made via the temporary variable (like modifying a property or calling a method) will persist in the map.
Does MATLAB have a way to create a dynamic Object storing array?
3 次查看(过去 30 天)
显示 更早的评论
I have a large number of a single type of Object, which has a few properties such as a unique ID. I need a way to store these objects in an array-like structure.
The problem is that in my script, these objects are constantly being deleted, and new Objects constantly being created.
I want a way to store my objects in such a way that they can be looked up with an integer ID, but I don't want to have to keep track of empty array spaces (which would come about if when Objects are deleted).
Basically, I'm looking for the equivalent of an ArrayList (google search may help). I've looked at containers.Map Objects, but they don't let me edit the Object Properties or call Object Methods directly from the container.
Does anyone know if such a thing exists in MATLAB?
0 个评论
回答(1 个)
Abhipsa
2025-6-6
I understand that you are looking for a dynamic, array-like structure in MATLAB to store and access objects by integer ID without managing empty slots, and with support for direct property/method access.
You can follow the below steps to achieve the desired behaviour in MATLAB:
The below code snippet demonstrates a handle class:
classdef MyObject < handle
properties
ID
Value
end
methods
function obj = MyObject(id, val)
obj.ID = id;
obj.Value = val;
end
function displayInfo(obj)
disp(['ID: ' num2str(obj.ID) ', Value: ' num2str(obj.Value)]);
end
end
end
The properties of the class can be modified using container as below:
% Create Map
objMap = containers.Map('KeyType','int32','ValueType','any');
% Add object
obj1 = MyObject(1, 42);
objMap(obj1.ID) = obj1;
tempObj = objMap(1); % Get the handle object
tempObj.Value = 100; % Modify property
remove(objMap, obj1.ID); %delete the object
I hope this helps you.
1 个评论
Walter Roberson
2025-6-6
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!