Advertisement
Guest User

global and workspace

a guest
Nov 30th, 2014
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.06 KB | None | 0 0
  1. %% Problem: pass variables efficiently to f2 without globals or workspace
  2. % % uncomment and run this once: then comment it and run the code.
  3. % % I saved the function under the name functiontester.m
  4. % Aa1 = 1;
  5. % Bb1 = 2;
  6. % x0_001 = 0.1
  7. % x0_002 = 0.2
  8. % constant_1 = 0.3
  9. % constant_2 = 0.4
  10. % save ('w.mat')
  11.  
  12. function f1_v3 % parent function that does the solving
  13.  
  14. clc
  15. clear all
  16. tic
  17.  
  18. load w.mat;
  19.  
  20. A=rand(100,2)
  21. % Ive got several loops before this function
  22. for i=1:100 % with loops before this, I have to call it >10000 times
  23. x0=[x0_001 * A(i,1), x0_002 * A(i,2)]
  24. options = optimset('MaxFunEvals', 1000,'MaxIter', 1000, 'Display', 'on');
  25. [x,fval,exitflag,output,jacobian] = fsolve(@f2v3,x0,options) % calling f2
  26. end
  27. toc
  28. end
  29.  
  30.  
  31. function F=f2v3(x) % almost all my variables are used here
  32. % pick your poison - either comment load w or globals. I want neither.
  33.  
  34. % load w.mat;
  35. global Aa1 Bb1 constant_1 constant_2
  36.  
  37. Aa1 = x(1)
  38. Bb1 = x(2)
  39.  
  40. r_1 = constant_1*Aa1*Bb1
  41. r_2 = constant_2*Aa1+Bb1
  42.  
  43. F = [Aa1 - Bb1                  
  44.     r_1 - r_2];  
  45. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement