Search code examples
functionmatlabargumentsfunction-parameter

MATLAB: Is there a method to better organize functions for experiments?


I will run a set of experiments. The main method evaluated has the following signature:

[Model threshold] = detect(...
    TrainNeg, TrainPos, nf, nT, factors, ...
    removeEachStage, applyEstEachStage, removeFeatures);

where removeEachStage, applyEstEachStage, and removeFeatures are booleans. You can see that if I reverse the order of any of these boolean parameters I may get wrong results.

Is there a method in MATLAB that allows better organization in order to minimize this kind of error? Or is there any tool I can use to protect me against these errors?


Solution

  • Organization with a struct

    You could input a struct that has these parameters as it's fields.

    For example a structure with fields

    setts.TrainNeg
         .TrainPos
         .nf
         .nT
         .factors
         .removeEachStage
         .applyEstEachStage
         .removeFeatures
    

    That way when you set the fields it is clear what the field is, unlike a function call where you have to remember the order of the parameters.

    Then your function call becomes

    [Model threshold] = detect(setts);
    

    and your function definition would be something like

    function [model, threshold] = detect(setts)
    

    Then simply replace the occurrences of e.g. param with setts.param.

    Mixed approach

    You can also mix this approach with your current one if you prefer, e.g.

    [Model threshold] = detect(in1, in2, setts);
    

    if you wanted to still explicitly include in1 and in2, and bundle the rest into setts.

    OOP approach

    Another option is to turn detect into a class. The benefit to this is that a detect object would then have member variables with fixed names, as opposed to structs where if you make a typo when setting a field you just create a new field with the misspelled name.

    For example

    classdef detect()
    properties
      TrainNeg = [];
      TrainPos  = [];
      nf = [];
      nT = [];
      factors = [];
      removeEachStage = [];
      applyEstEachStage = [];
      removeFeatures =[];
    end
    methods
      function run(self)
        % Put the old detect code in here, use e.g. self.TrainNeg to access member variables (aka properties)
      end
    end