How does Matlab uses memory inside a function?

10 views (last 30 days)
I am doing a program that works with very large matrices (several gigabytes). I would like to understand what happens when I pass a large matrix from the matlab workspace into a function. Is there a copy of the matrix within the function or it exists ithin the function only as a reference to the original workspace variable?
I tought that a new copy of the variable exists within the function but when I used the "memory" function to check memory usage there was no change in the memory used after the function was called.
Example;
  • Create a large matrix in matlab workspace and check memory usage
A = rand(100000,10000); % 8 GB
memory
  • Create a simple function that uses the large matrix as an input
function test(AA)
memory % check 1 - memory does not increase by 8 GB
AA = AA + 1;
memory % check 2 - memory increases by 8 GB
end
  • Place a breakpoint into the function and run it with the large matrix
test(A)
  • Compare the memory usage of matlab before the function was run and at the two points inside the function
In the first check in the function no additional memory is used. It seems that variable AA points to the same memory as variable A in matlab workspace. In the second check after the variable is changed additional 8 GB of memory is used. Apparently a new copy of the variable is written to the memory.
What happens with the memory inside the function? Does it mean that if I do not edit the large matrix no additional memory is used?

Accepted Answer

Bjorn Gustavsson
Bjorn Gustavsson on 12 May 2022
Matlab is very clever in memory usage in functions, pass-by-reference-copy-on-modification. So as long as you only take values out of the matrix no new matrix gets created, at the point you add 1 to A then a new local copy is created. Matlab also use in-place operations on data, see Loren's post: inplace_1 (there's also an _2 post with additional information, and hopefully the support for this has improved since 2007)
HTH

More Answers (0)

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!