Search code examples
matlabfunctionworkspace

Does A Function's Workspace Duplicate A Variable Input?


I have defined in the base Workspace a variable

a = ones(10);

And I would like to create function that inputs a vector vec1 and gives back vec2:

function vec2 = myfun(vec1)

Operations with vec1

end

Lets make

b = myfun(a);

In the Workspace of myfun we will have a variable called vec1 which has the same values as a but it is not in the base Workspace.

When being in Debugging Mode and using

dbup;

I can see two different variables a and vec1 in base and myfun Workspaces respectively.

Is myfun duplicating the variable a in two different Workspaces (and therefore using more memory)?

If this is not the case, how does it work? Is it a pointer assigning two different names to the same information?

Thank you in advance.


Solution

  • MATLAB uses a system commonly called "copy-on-write" to avoid making a copy of the input argument inside the function workspace until or unless you modify the input argument. If you do not modify the input argument, MATLAB will avoid making a copy. For instance, in this code:

    function y = functionOfLargeMatrix(x) 
         y = x(1);
    

    MATLAB will not make a copy of the input in the workspace of functionOfLargeMatrix, as x is not being changed in that function. If on the other hand, you called this function:

    function y = functionOfLargeMatrix2(x) 
          x(2) = 2;  
          y = x(1);
    

    then x is being modified inside the workspace of functionOfLargeMatrix2, and so a copy must be made.