- 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?
조회 수: 4 (최근 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!