Constants in MATLAB

前端 未结 8 902
孤城傲影
孤城傲影 2020-12-04 21:44

I\'ve come into ownership of a bunch of MATLAB code and have noticed a bunch of \"magic numbers\" scattered about the code. Typically, I like to make those constants in lan

相关标签:
8条回答
  • 2020-12-04 22:18

    Any way you do it, it will still be somewhat of a kludge. In past projects, my approach to this was to define all the constants as global variables in one script file, invoke the script at the beginning of program execution to initialize the variables, and include "global MYCONST;" statements at the beginning of any function that needed to use MYCONST. Whether or not this approach is superior to the "official" way of defining a function to return a constant value is a matter of opinion that one could argue either way. Neither way is ideal.

    0 讨论(0)
  • 2020-12-04 22:19

    My way of dealing with constants that I want to pass to other functions is to use a struct:

    % Define constants
    params.PI = 3.1416;
    params.SQRT2 = 1.414;
    
    % Call a function which needs one or more of the constants
    myFunction( params ); 
    

    It's not as clean as C header files, but it does the job and avoids MATLAB globals. If you wanted the constants all defined in a separate file (e.g., getConstants.m), that would also be easy:

    params = getConstants();
    
    0 讨论(0)
提交回复
热议问题