Spyros
Spyros

Reputation: 289

Minimize inputs by loading values in MATLAB functions

In MATLAB is it be better (as far as optimization is concerned):

1)To have a function "foo" with a lot of inputs that come from the outputs from other functions

or

2)Save at the end of the functions the results to a results.mat file and load it in the "foo" function and minimize its inputs this way?

Upvotes: 0

Views: 70

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

almost always: option 1.

As option 2 depends on file IO, and thus one write and one read to/from a hard disk, SSD or similar, it will likely lose out against keeping variables in RAM. Moreover, if you pass arguments to a function, and that function only reads them, no explicit copies of that variable are made. This is not true for the .mat file solution, as something that you already have in memory will be explicitly copied onto an extremely slow device (HDD, SSD), and then again read back into memory from the extremely slow device, just to save on a few input arguments.

So, unless you're working with big data sets and your variables give you out-of-memory errors, keep everything in RAM as much as possible.

You can minimize argument count by simply collecting data in a container data type. MATLAB has cell and struct for this purpose (or classdef, if you include value classes). You can transform this:

[outarg1, outarg2] = function(arg1, arg2, arg3,...)

into

[outarg1, outarg2] = function(S)

where

S = struct(...
    'arg1', function1(X),...
    'arg2', function2(X,Y,Z),...
    'arg3', function3(X,Z),...
    %// etc.
);

or

S = {
    function1(X)
    function2(X,Y,Z)
    function3(X,Z)
    %// etc.
}

or similar. Or you can make use of the special cell/functions called varargin/nargin and varargout/nargout:

varargout = function(varargin)

    % rename input arguments
    arg1 = varargin{1};
    arg2 = varargin{2};
    %// etc.

    % assign all output arguments in one go
    [varargout{1:nargout}] = deal(outargs{:}));

end % function

You can read more about all these things by typing help <thing> on the MATLAB command prompt. For example,

help cell

will give you a wealth of information on what a cell is and how to use it.

Upvotes: 1

Amresh
Amresh

Reputation: 816

I think using global variables is a better way to optimize memory and processing requirements. you can use keyword global.

Upvotes: 0

Related Questions