MATLAB: How to save variables in one function so as they can be used in other functions? so they can be used

variables

variables that are created in one function disappear when my script goes to another function. How do I make them available for all functions?

Best Answer

  • How to pass arguments is covered quite clearly in the introductory tutorials. All beginners should do these tutorials. They introduce how MATLAB works:
    And if they want more detailed info, then any internet search engine can help them find this page:
    That page tells the inquisitive reader that the best (fastest, most robust) way to pass data from one workspace to another (or as you call it, from one function to another) is to pass arguments. Like this:
    function [A,B] = myFun(X,Y);
    A = mean(X);
    B = X+Y;
    end
    and inside another function you can simply call that function with those arguments:
    mat = 1:5;
    val = 0;
    [out,tmp] = myFun(mat,val);
    and bingo! There are the values that you need, in the workspace of another function, with whatever variable names you want them to have. Of course there is also lots of fineprint (scoping, filenames, local vs main, etc), but the more you start reading the more you will learn.
    Note that some beginners believe that they should try to pass every variable from one workspace to the next: not only is this quite hard to do, it is a bad idea. The whole purpose of functions is to encapsulate some behavior, and what happens inside is irrelevant. Consider the sine function:
    Y = sin(X)
    we do not know what temporary variables are inside, nor does it matter. The only things that matters is that the input and output are precisely defined. Write your functions the same way.