Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best alternative to MATLAB's global variables

I'm writing a MATLAB application which has many functions spread over different files. I have a logger, which is a struct with a function pointer, and I use it to log information for the user to see (that is, which function is currently executing, calculation results, etc.). The reason I use a struct for my logger and not simply fprintf() is that I could easily replace it with an XML logger, HTML logger, etc. in the future.

Since my code is composed of many functions calling each other, I declared my logger struct as global, so I don't have to pass it to all my many functions. However, everywhere I look I see that global variables are evil incarnate in MATLAB and will slow my program down considerably.

Is there a way to have variables available across files without necessarily passing them as input parameters, and without suffering from severe performance penalty?

like image 961
dzisner Avatar asked Jan 10 '12 18:01

dzisner


2 Answers

You can also use persistent keyword inside a file, and allocate the logger there.
It is similar in some ways to the static keyword in C++. It is also an implementation of the Singleton pattern.

function CallLogger(st)
    persistent logger;
    if isempty(logger)
        %Allocate new logger
    end
    logger.disp(st);
end

It is better than global because
1. No one can destroy your logger without your knowledge.
2. No one even knows about this object, because it is limited to the function scope

By the way, I don't agree that global has a performance issue. It is just not a good practice, in terms of Software Engineering.

like image 126
Andrey Rubshtein Avatar answered Oct 06 '22 06:10

Andrey Rubshtein


Better than invoking persistent variables in a function (which, for example, won't be saved if you save and then reload your workspace) would be to move from function + struct to object: that is, you should look into MATLAB's object oriented programming.

like image 31
lsfinn Avatar answered Oct 06 '22 07:10

lsfinn