0

I wanted to ask how values in MATLAB are returned? Are they copied or passed by reference?

take a look at this example with matrix A:

function main
    A = foo(10);

    return;
end

function [resultMatrix] = foo(count)
    resultMatrix = zeros(count, count);
    return;
end

Does the copy operation take place when function returns matrix and assigns it to variable A ?

Benas
  • 2,106
  • 2
  • 39
  • 66

1 Answers1

2

MATLAB uses a system known as copy-on-write in which a copy of the data is only made when it is necessary (i.e. when the data is modified). When returning a variable from a function, it is not modified between when it was created inside of the function and when it was stored in a different variable by the calling function. So in your case, you can think of the variable as being passed by reference. Once the data is modified, however, a copy will be made

You can check this behavior using format debug which will actually tell us the memory location of the data (detailed more in this post)

So if we modify your code slightly so that we print the memory location of each variable we can track when a copy is made

function main()
    A = foo(10);

    % Print the address of the variable A
    fprintf('Address of A in calling function: %s\n', address(A));

    % Modify A
    B = A + 1;

    % Print the address of the variable B
    fprintf('Address of B in calling function: %s\n', address(B));
end

function result = foo(count)
    result = zeros(count);

    % Print the address of the variable inside of the function
    fprintf('Address of result in foo: %s\n', address(result));

end

function loc = address(x)
    % Store the current display format
    fmt = get(0, 'format');

    % Turn on debugging display and parse it
    format debug
    loc = regexp(evalc('disp(x)'), '(?<=pr\s*=\s*)[a-z0-9]*', 'match', 'once');

    % Revert the display format to what it was
    format(fmt);
end

And this yields the following (or similar) output

Address of result in foo: 7f96d9d591c0
Address of A in calling function: 7f96d9d591c0
Address of B in calling function: 7f96d9c74400

As a side-note, you don't need to explicitly use return in your case since the function will naturally return when it encounters the end. return is only necessary when you need to use it to alter the flow of your program and exit a function pre-maturely.

Community
  • 1
  • 1
Suever
  • 64,497
  • 14
  • 82
  • 101