Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deleting a huge matrix after passing its local copy to a function in Matlab

Considering we have a huge matrix called A and we pass it to the function func(A) wherein func I do a set of computations like:

func(A):

B=A;

%% a lot of processes will happen on B here 

return B;

end

The fact is that as soon as I pass A to B I would not have anything to do with A anymore in my Matlab session so it takes an unnecessary space in memory. Is it possible to remove its instance in the scope of the script that called func?

like image 624
CoderInNetwork Avatar asked Jan 29 '23 19:01

CoderInNetwork


1 Answers

Using evalin with the option caller you can evaluate expression clear A:

function A = func(A)
    evalin('caller', 'clear A')
    A(1) = 5;
end

However we usually don't know the name of the input variable so we can use inputname to get the actual name of the workspace variable:

function A = func(A)
    name = inputname(1);
    if ~isempty(name)
        evalin('caller', ['clear ' name])
    end
    A(1)=4;
end

1.Here inputname(1) means the actual name of the first argument.

2.Work directly with A because if you copy A into B the function scope will have two copies of A.

like image 157
rahnema1 Avatar answered May 10 '23 22:05

rahnema1