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:
normalElapsed 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 sofsig = 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
ticfor i=1:max_iter k(i) = normrnd(y1,sig)/y2*y3*y4/y5*y6/y7/y1*y2 + y1*y3*y5/y2;endtoc% perform calculations with variables defined with assignin('caller',...;
ticfor i=1:max_iter k_a(i) = normrnd(x1,sig)/x2*x3*x4/x5*x6/x7/x1*x2 + x1*x3*x5/x2;endtocendfunction 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
Best Answer