Dos varargout make a copy of the output variables?
4 views (last 30 days)
Show older comments
I'm trying to optimize some code for memory use and I'm wondering if the varargout variable makes a copy of the variables which are assigned to it. For example:
function varargout = foo(bar)
C={rand(bar,bar^2,bar^3), false(100,100,100))};
varargout(1:nargout)=C(1:nargout);
end
If bar is a big number than C will be huge and if a copy needs to be made at any stage an out of memory error may occur. My gut tells me no copy is made but I can't seem to find an explicit answer.
0 Comments
Accepted Answer
James Tursa
on 19 Mar 2018
To see how MATLAB returns variables from subroutines you can run the following code:
function x = junkdemo(n)
x = rand(n,n)
return
end
Then at the command line:
>> format debug
>> y = junkdemo(5)
x =
Structure address = 7a89ed0
m = 5
n = 5
pr = 240cdb70
pi = 0
0.8147 0.0975 0.1576 0.1419 0.6557
0.9058 0.2785 0.9706 0.4218 0.0357
0.1270 0.5469 0.9572 0.9157 0.8491
0.9134 0.9575 0.4854 0.7922 0.9340
0.6324 0.9649 0.8003 0.9595 0.6787
y =
Structure address = 7a89648
m = 5
n = 5
pr = 240cdb70
pi = 0
0.8147 0.0975 0.1576 0.1419 0.6557
0.9058 0.2785 0.9706 0.4218 0.0357
0.1270 0.5469 0.9572 0.9157 0.8491
0.9134 0.9575 0.4854 0.7922 0.9340
0.6324 0.9649 0.8003 0.9595 0.6787
You can see that MATLAB created x inside the junkdemo function. This x variable has a structure address of 7a89ed0 and a data address of 240cdb70. A shared data copy of x is what got returned to the caller and stored in y. The y variable has a structure address of 7a89648 (different from x) but the data address of y is the same as x, namely 240cdb70. I.e., it is only a new variable header that gets created in the return process (containing variable class, size, etc). The data itself is not copied ... only the pointer.
This is true on input as well as output, btw. The act of passing variables in or out of a function does not, in and of itself, cause the data to be copied. It is only when you change an element of a variable that is sharing data pointers with another variable that will cause MATLAB to make a deep data copy.
More Answers (1)
Walter Roberson
on 19 Mar 2018
MATLAB is a copy-on-write system. When a copy of the contents of C is required by the assignment to varargout, the internal pointers to the entries are copied and the reference count of the nodes are incremented.
See Also
Categories
Find more on Variables 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!