Efficiently updating variables inside an object

Hi. I have a object (foo) with two huge array variables (array1, array2). How do I call the obj's methods and have one (or the other or both) variable updated without needing an external reassignment of the object?
classdef foo
properties
array1 = []; array2 = [];
end
methods
function obj = foo()
% init array1/array2 with some huge database-sized values
end
function y = bar(obj, x)
if x > 0
% make changes to array1
y = x-1;
elseif x == 0
% make changes to array1 and array2
y = x;
else
% make changes to array2
y = x+1;
end
end; % bar
end; % methods
end
The real problem has (1) a hundred of these giant arrays, (2) method bar is called recursively, sometimes changing array1 and other times array2, and (3) there are other methods that needs access to the arrays so persistents inside func bar probably won't work. My problem is if I do:
function [y, obj] = bar(obj,x)
% code
end
a = foo();
[y, a] = a.bar(5)
wouldn't I be updating and copying over the entire object eventhough only one of the hundreds of variables is being updated? Or is MATLAB copy-on-write optimized to copy only the parts that's changed? Or is a = a.bar() not considered a copy-on-write in that it makes no copies but merely reassigns the pointers? I don't want the program to spend hours/days making copies of variables that never changed.
Any ideas how I can do this? Many thanks!!
(I'm currently running R2016 but I can install R2019 if the solution requires)

1 Comment

I wonder if there is any way to modify an array that is a property (private) in the inplace manner, avoid totally the copy-on-write.
Did some quick tests and I did not find any way to do it.
The strange thing is I cannot even do for regular array under R2020a. I swear that can be done in earlier release. Odd.

Sign in to comment.

 Accepted Answer

Matt J
Matt J on 26 Aug 2020
Edited: Matt J on 26 Aug 2020
Or is MATLAB copy-on-write optimized to copy only the parts that's changed?
It is. For the purposes of copy-on-write, Matlab treats different object properties as if they were separate variables. The same is true for struct fields and cell array elements.

1 Comment

Thanks, Matt. Since Matlab can handle memory efficiently, I'll just do a normal a = a.bar assignment. Many thanks!

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2016b

Community Treasure Hunt

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

Start Hunting!