How to Copy a struct that has existing references/handles and break the link to the original data

1 view (last 30 days)
I have an RGBD camera which via various scripts provides a struct for a depth image, and similarly an RGB image each frame.
I am trying to save the information for each frame in a cell array while looping like
buffer{j} = curr_frame_depth_struct
so that at the end i have
buffer = {frame1_struct, frame2_struct, etc}
The problem comes that at the start of the loop the API calls to take a new image, and this new image information is then transferred to all the saved previous depths structs in buffer. (I'm guessing theres some amount of copy by pointers/references). This means that at the end i have a cell array of say 50 frames, where every frame contains the same information, which is the last information collected.
buffer = {frame50_struct, frame50_struct, etc, frame50_struct}
Is there a way to break this point/reference without saving the variable to a file and loading it every loop. I've tried the matlab.mixin.Copyable. copy() function but it is the wrong type.
Thanks

Answers (1)

Praveen Reddy
Praveen Reddy on 12 May 2023
Hi Thomas,
I understand that you are trying to append struct in a cell array and confused if MATLAB is exhibiting pass by reference. For built-in data types, MATLAB always passes arguments 'by value'. If the input is a handle object, then pass by reference is exhibited. I suggest to pass the buffer as an input argument to the function where depth of an image struct is being read, add the struct to the buffer. Below is an example you can refer to:
buffer={};
for i=1:10
buffer=fillBuffer(buffer);
end
function buffer=fillBuffer(buffer)
for j=1:5
sample_struct.a = randi([10,20],1,1);
sample_struct.b = randi([10,30],1,2);
buffer{end+1}=sample_struct;
end
end

Community Treasure Hunt

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

Start Hunting!