How are structs handled when passed to a function?
Show older comments
Hi, I a question about how structs are handled when they are used as input arguments to functions. I know about "copy on write", namely that matrices are passed by a reference unless they are modified and thus are copied. However, I get the impression that structs actually uses pointers or references to the data fields, and this makes structs different from matrices. This is why I wonder, how are the "copy on write" used when I have struct input arguments?
Examples: 1: matrix)
function out = fun2(in)
out = in; % Return reference
2: matrix)
function out = fun2(in)
in(2,5) = 4; % Matlab creates a copy
out = in;
3: struct, what happens here?)
function out = fun3(in)
in.fieldA = rand(3); % What happens here?
out = in;
1 Comment
When I was looking into this type of behaviour (though not for structs) I just created a matrix large enough that it showed up in my Task Manager memory analysis so I could see at what point a copy of the data was made (if at all) when calling a function.
You should be able to do the same with a struct if you make your fieldA something more like rand(20000).
I haven't investigated structs myself so wouldn't want to give an answer without testing it which I don't really have time for at the moment. I would expect them to work similarly to matrices though. Certainly if I add or edit a field within a function I do not expect that field to be added or changed in the calling function's workspace.
Accepted Answer
More Answers (1)
Bill Tubbs
on 2 May 2021
Edited: Bill Tubbs
on 2 May 2021
Seems that MATLAB makes a complete copy of a struct when it is passed to a function if any element is changed by the function (see demo script below). So is there no way to pass a reference to a struct to a function? From this article it would seem not.
s.a = 1;
s.b = 2;
s2 = change_struct(s);
assert(s.a == 1)
assert(s2.a == 2)
s.b = -1;
assert(s2.b == 2)
function s2 = change_struct(s)
s.a = s.a + 1;
s2 = s;
end
Categories
Find more on Structures 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!