Memory-Allocation for function calls of form x = f(x) in MATLAB

后端 未结 1 816
星月不相逢
星月不相逢 2020-12-18 13:33

In my code, I have lots of places where I invoke functions of the form

X = f(X)

and X can be a rather large matrix. In my special case, I

相关标签:
1条回答
  • 2020-12-18 14:11

    Whether a copy is made of the input arguments or not when calling a function in MATLAB depends upon what happens inside of the function.

    MATLAB uses a system referred to as copy-on-write. This means that if you pass a large variable to a function as an input, as long as you do not modify the variable within that function, the variable will not be copied into the workspace of the function and the function will instead read the data from it's current location in memory.

    function Y = func(X)
        Y = X + 1;
    end
    

    If you are modifying the variable within the function, then a copy of the input variable is made and placed into the local workspace of the function.

    function X = func(X)
        X = X + 1;
    end
    

    There is more information on Loren's Mathworks blog.

    An easy way to determine if a copy of the data is made or not is to use the undocumented format debug mode which will show you where the data for a given variable is stored in memory.

    format debug
    
    %// Create a variable a and show where debug info
    a = [1,2]
    
    %// Structure address = 141f567f0
    %// m = 1
    %// n = 2
    %// pr = 7f9540b85e20
    %// pi = 0
    %//      1     2
    
    %// Assign b = a but don't modify
    b = a
    
    %// Structure address = 141f567f0
    %// m = 1
    %// n = 2
    %// pr = 7f9540b85e20  <= POINTER TO DATA REMAINED UNCHANGED
    %// pi = 0
    %//      1     2
    
    %// Modify (Will create a new copy)
    b = b + 1
    
    %// Structure address = 141f55b40
    %// m = 1
    %// n = 2
    %// pr = 7f953bcf1a20   <= POINTER TO DATA CHANGED (COPY)
    %// pi = 0
    %//      2     3
    

    If you prefer you can use this little anonymous function I've created to inspect the memory location of any particular variable.

    memoryLocation = @(x)regexp(evalc('disp(x)'), '(?<=pr\s*=\s*)[a-z0-9]*', 'match')
    
    a = [1,2];
    memoryLocation(a)
    %// 7f9540b85e20
    
    b = a;
    memoryLocation(b)
    %// 7f9540b85e20
    
    b = b + 1;
    memoryLocation(b)
    %// 7f953bcf1a20
    

    As a bit of a side-note, I would recommend against using feval throughout your code and instead just use the function names directly.

    0 讨论(0)
提交回复
热议问题