assignin caller to variables - performance issues
Show older comments
I have variables outside a particular function, which I want to put in a workspace of another function. I do this by using assignin('caller'.... As a test case, I did the same scenario, one as described above, and the other as simply defining a duplicate scenario within the main function (code below)
Quite simply there is a performance issue with this, here are my results:
normal
Elapsed time is 1.613414 seconds.
assignin('caller',...
Elapsed time is 1.849663 seconds.
The timing is not significant here, but it does matter as number of (single) variables increase. I see orders of magnitude performance decrease in my work. I checked that both versions give the exact same results at the end
note: For some strange reason in my code not present here, I have many matrices and single-variables each involved in operations and computations. If matrices are called with assignin('caller'..., there is literally no performance hit. With single variables, the problem in performance arises.
CODE
function sof
sig = 0.3;
max_iter = 100000;
% in functiond efined variables
y1 = 2.5;
y2 = 7.3;
y3 = 3.4;
y4 = 7.2;
y5 = 2.2;
y6 = 1.7;
y7 = 9.2;
k = zeros(1,max_iter);
% defined elswhere using assignin 'caller'
get_vars (max_iter);
% perform calculations with variables defined here
tic
for i=1:max_iter
k(i) = normrnd(y1,sig)/y2*y3*y4/y5*y6/y7/y1*y2 + y1*y3*y5/y2;
end
toc
% perform calculations with variables defined with assignin('caller',...;
tic
for i=1:max_iter
k_a(i) = normrnd(x1,sig)/x2*x3*x4/x5*x6/x7/x1*x2 + x1*x3*x5/x2;
end
toc
end
function get_vars (mrange)
assignin('caller','x1',2.5);
assignin('caller','x2',7.3);
assignin('caller','x3',3.4);
assignin('caller','x4',7.2);
assignin('caller','x5',2.2);
assignin('caller','x6',1.7);
assignin('caller','x7',9.2);
assignin('caller','k_a',zeros(1,mrange ));
end
Accepted Answer
More Answers (1)
Walter Roberson
on 28 Dec 2013
Use nested functions and shared variables.
function sof
...
x1 = []; %assign values to variables _before_ the call
x2 = [];
x3 = [];
x4 = [];
x5 = [];
x6 = [];
x7 = [];
k_a = [];
% assigned within as shared variables
get_vars(max_iter);
....
function get_vars(mrange) %nested function
x1 = 2.5;
x2 = 7.3;
x3 = 3.4;
x4 = 7.2;
x5 = 2.2;
x6 = 1.7;
x7 = 9.2;
k_a = zeros(1,mrange);
end %end get_vars
end %end sof
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!