shaloo shaloo
shaloo shaloo

Reputation: 213

How does function work regarding to the memory usage?

When you are using function in MATLAB you have just the output of the function in the work space and all the other variables that maybe created or used in the body of that function are not shown. I am wondering how does function work? Does it clear all other variables from memory and just save the output?

Upvotes: 0

Views: 58

Answers (1)

Adriaan
Adriaan

Reputation: 18177

function acts like a small, isolated programming environment. At the front end you insert your input (e.g. variables, strings, name-value pairs etc). After the function has finished, only the output is available, discarding all temporarily created variables.

function [SUM] = MySum(A)
    for ii = 1:length(A)-1
        SUM(ii) = A(ii)+A(ii+1);
        kk(ii) = ii;
    end
end

>> A=1:10
>> MySum(A)

This code just adds two consecutive values for the input array A. Note that the iteration number, stored in kk, is not output and is thus discarded after the function has completed. In MATLAB kk(ii) = ii; will be underlined orange, since it 'might be unused'.

Say you want to also retain kk, just add it to the function outputs:

function [SUM,kk] = MySum(A)

and keep the rest the same.

If you have large variables that you only use up to a certain point and wish them not clogging up your memory whilst the function is running, use clear for that:

function [SUM] = MySum(A)
    for ii = 1:length(A)-1
        SUM(ii) = A(ii)+A(ii+1);
        kk(ii) = ii;
    end
clear kk
end

Upvotes: 1

Related Questions