Search code examples
oopmatlabdicomcoupling

MATLAB and the use of global variables?


I am writing a tool for dicom images and spectroscopy and there is a lot of shared data I want to use between the functions I am making. I have GUI that I made and the different sliders and buttons use a lot of this shared data from the dicom files.

I have been using global variables to store information that all of these functions share. I have a lot of globals currently. I have been taught to avoid global variables if possible because of increasing coupling. Would it be better to read in the data from the dicom file in each function? This seems redundant. Would using MATLAB as object-oriented help?


Solution

  • Since you mention you are working with a GUI and wanting to share data between the control callbacks, I would suggest designing your code using nested functions. The overall code would look something like this:

    function dicomGUI
    
      %# Initialize your GUI here, linking the control callbacks to the
      %#   nested functions below:
    
      hLoad = uicontrol('Style', 'push', 'String', 'Load file', ...
                        'Callback', @load_file);
      ...
    
      %# Initialize the data variables for the DICOM files here:
    
      data = [];  %# Shared among nested functions
      ...
    
      %# Below are all the nested functions your controls will use:
    
      function load_file(hSource, event)
        data = ...;  %# Load the data here
      end
      ...
    
    end
    

    Not only does this let you put all your GUI code in one m-file, but it simplifies the control callbacks and makes it easy for them to share variables in the workspace of the parent function dicomGUI. An example of this approach, along with other suggestions for sharing data between GUI controls, can be found on this documentation page: Share Data Among a GUI's Callbacks.

    As Chris mentions, this could become a very large m-file for a large and intricate GUI. To keep the file size down in such a case I would suggest making the body of each callback simply a call to a function in a separate file which accepts the shared data variables, performs whatever work is necessary, then returns the modified data to the same shared variables. For example:

    function transform_callback(hSource, event)
    
      %# Apply some transform to the data:
      data = transform_data(data);
    
      %# If the above changes the GUI (disabling controls, changing a
      %#   display, etc.), then those changes should be made here.
    
    end