Home > Mobile >  Is there a way for a matlab function to access all variables in a script
Is there a way for a matlab function to access all variables in a script

Time:09-17

I have a script with lots of variables (10-30), and in a for loop I do some processing using basically every variable. I have a helper script so that the interior of the loop looks clean.

main script

a=2;b=5;c=8;d=10;%and many many more
for i=1:1000
    helper;
end

I want to turn helper into a function, primarily because this would allow me to have the helper script (now a function) at the bottom of the main file. But I definitely do not want to individually pass every variable and every variable that I have yet to need in this project.

What I really need is a goto, but matlab doesnt have it.

CodePudding user response:

There are many solutions to this. In rinkert's comment you've gotten the only one that is good coding practice: put the variables in a struct, then pass the struct into your function. I highly recommend that you do that. Using nested functions is not a terrible solution either, though it could be a lot more difficult to manage (variable visibility rules are funny in nested functions, I find it confusing at times).

Here I'm going to give you the worst possible solution: evalin. You should not do this, I post this here for educational purposes only.

evalin allows a function to retrieve a variable in the caller's workspace:

a=2;b=5;c=8;d=10;%and many many more
for i=1:1000
    helper;
end

function helper
    % NEVER DO THIS IN PRACTICE
    a = evalin('caller','a');
    b = evalin('caller','b');
    c = evalin('caller','c');
    d = evalin('caller','d');
    % do computations....
    assignin('caller','result',result);
end

Note that a function result = helper(a,b,c,d) is much more efficient and much easier to maintain because it's clear what is going on. evalin makes for surprising results, and assignin even more so. Do not use this.

There are a few legitimate uses of these functions. For example, I've written a GUI that allows a MATLAB user easier access to a set of functions, but is meant to work in conjunction with the interactive MATLAB command prompt. The GUI would fetch variables from the 'base' workspace, evaluate function calls in the 'base' workspace, and write new variables to the 'base' workspace. Running a function within the GUI is just like running it at the command prompt. There is no other way of accomplishing this other than using evalin and assignin.

CodePudding user response:

although it's not good coding conduct, you could use global variables : for example :

global a;
a= 5;

function out =test()
    global a;
    out=2*a;
end 
  • Related