How do I add a new element to an object array using pass by reference?
Show older comments
Hello,
I am trying to use pass by reference using handle objects.
The scenario I have right now is I have an array of handle objects defined by:
classdef unit < handle
and I'd like to pass an array of such an object to a function which in turn sets a callback to a button that once pressed, should add a new element to that array. I have managed to pass the array through to the callback function. When I change the value of the properties of any of the original elements, the original array gets updated, as expected. However, when I add an element, the new element is lost when the callback function completes, as expected I suppose.
But since I cannot return anything from a callback, what method can I use to add this element and have it update the original object? A couple potential solutions I've thought of:
1. Do I need to pre-augment the array? But I do not know if I need to augment the array until the callback executes.
2. Do I have to create another handle class that is used simply to hold this "unit" object array in a pass by reference scenario? Seems awfully clunky to me.
Thanks in advance!
8 Comments
Daniel Ko
on 27 Oct 2020
per isakson
on 28 Oct 2020
"[...] when I add an element" How do you add a new object to the array?
J. Alex Lee
on 28 Oct 2020
I don't think this is an issue of your class being a handle. The object array will hold references to instances, but the array itself wouldn't be a handle, right?
It sounds like you just need a way to pass your object array variable around in your app, such as by making it a property of your app class. If you're using an older style of making apps, look into getappdata/setappdata.
Daniel Ko
on 28 Oct 2020
Daniel Ko
on 28 Oct 2020
J. Alex Lee
on 28 Oct 2020
are you sure your design should be passing around the entire app around different functions, or should your app class define the relevant methods that can operate on different properties of the app? do you need access to unitArray from outside the app?
Daniel Ko
on 29 Oct 2020
J. Alex Lee
on 29 Oct 2020
The solution by per isakson addresses allocation of an object array, plus some mechanisms to track the size. Is this the question you wanted answered? Or are you asking about growing the object array within an app and then later accessing that array from outside the app?
Accepted Answer
More Answers (0)
Categories
Find more on Data Type Identification in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!