I am trying to create a function that stores a very large variable for use each time the function is called. I have a function myfun(x,y)
where y
is very large, and therefore slow to execute because MATLAB is pass-by-value. However, I only pass the variable y
once during execution of a program, creating a closure that is then passed off to another function to call repeatedly:
Y = create_big_matrix();
newfun = @(x) myfun(x,Y);
some_other_fun(newfun); % This calls newfun several times
I assume that each time newfun
is called, it copies the stored value of Y
to myfun
. This seems very inefficient. Is there a better way to implement newfun
so that Y
is only copied once, when the newfun
is created (and maybe when it's passed to some_other_fun
)?