Masan
Masan

Reputation: 345

Efficient way of passing data between MATLAB functions

I am solving a very large optimization problem. The objective function and constraint function needs numerous data. Currently I am passing the data as a structure to them.

myFS(X, Dat, g_Index, f_Index)  % Dat is a structure which includes many variables

Do you think it's an efficient way to reduce the elapsed time?

What better alternatives do exist?

Is this what the given answer, regarding to class definition, means?

 %% First we define the class in a separate file:
classdef myDataStructure < handle

    properties
 NRES;
 NOBJ;
 NVAR;
    end
    methods
        function obj = myDataStructure()
        end
    end
end

%% In another file where the main program is, we initialize the class.

Dat = myDataStructure();
%%  Initialize
Dat.NRES = 1;
Dat.NOBJ = 1;
Dat.NVAR = 1;
[myF, Dat_updated] = BBB(Dat);

%% Here we define the function and use the class

function [f, CalssDat] = BBB(CalssDat)
    x = CalssDat.NRES;
    y = CalssDat.NOBJ;
    z = CalssDat.NVAR;
    f = x + y + z;
    CalssDat.NOBJ = 2;
end

Upvotes: 0

Views: 219

Answers (1)

Tam&#225;s Szab&#243;
Tam&#225;s Szab&#243;

Reputation: 733

As far as I know, MATLAB does not actually copy the content of the data you pass to a function until the point when you modify it in the function itself - in which case it makes a local copy and that takes some CPU time.

Therefore, as long as Dat doesn't change inside myFS(), what you are doing now does not add any CPU overhead. In case you do change the values of Dat inside myFS() and want to return it, I can think of two ways to optimise it:

You can declare myFS() as: function [Dat, anythingElse] = myFs(X,Dat,g_Index, f_Index), which should prevent matlab from making a local copy.

Another approach is to use a class that derives from handle and have Dat be a member of that. This way, whenever you pass the object containing Dat, you only pass the object handle and not a copy of the object itself.

Example of the second approach:

classdef myDataStructure < handle

    properties
        p1FromDat;
        p2FromDat;

        %   .
        %   .
        %   .

        pNFromDat;
    end

    methods
        function obj = myDataStructure()
            % Add initialization code here if you want. Otherwise p1FromDat
            % ... pNFromDat are accessible from outside
        end
    end
end

Than, in your code:

Dat = myDataStructure();
Dat.p1FromDat = 1;
Dat.p2FromDat = 1;

And in your myFs() you use Dat exactly the same way as you used before.

Because myDataStructure derives from handle, the data inside will not be copied when you pass Dat around.

Do be careful with this, because when you change Dat in myFS(), the values will be changed outside the scope of myFS() as well.

Upvotes: 2

Related Questions