Matlab中常数值和相关参数的单独定义

Separate definition of constant values and dependent parameters in Matlab

在我的代码中,我有很多常量值和参数,这些值和参数在我的代码中很重要 space。

例如在 C++ 中,我会制作一个头文件和一个单独的文件,我将在其中将这些参数定义为,例如“const-type”并共享头文件使用主文件或其他 .cpp 文件。

如何在 MATLAB 中保持这种结构,值得吗?

一个例子:Coefficients.m 看起来如下:

classdef coefficients
    properties(Constant) 
        % NIST data
        A_N = 28.98641;
    end
end

另一个文件:Gas.m 我想在其中使用 A_N 如下所示:

function Gas()
  clear all
  clc
  
  import Coefficients.* % Does not work

  % A simple print
  Values.A_N        % Does not work
  coefficients.A_N  % Does not work
  Constant.A_N      % Does not work
end

有关使用 class 定义的提示,请参阅 this link。重点提示有:

  • 可以直接访问属性获取值
  • 可以添加给出常量单位的属性(强烈建议!)
  • 可以添加注释作为常量的帮助文本
  • doc 命令自动为此 classdef
  • 创建参考页

例如,

classdef myconstants
    properties(Constant)
        % g is the gravity of Earth
        % (https://en.wikipedia.org/wiki/Gravity_of_Earth)
        g = 9.8;
        g_units = 'm/s/s';
        % c is the speed of light in a vacuum
        c = 299792458;
        c_units = 'm/s';
    end
end

>> help myconstants.g

好的,假设 class coefficients 定义为:

classdef coefficients
    properties(Constant) 
        % NIST data
        A_N = 28.98641;
    end
end

此代码 必须 保存在名为 coefficients.m 的文件中(class 名称和文件名必须匹配以避免有时出现奇怪的效果)。

然后假设以下 Gas.m 文件:

function Gas()

    % Usage with "disp()"
    disp('The A_N coefficient taken from NIST data is:')
    disp(coefficients.A_N)
    
    % Usage with fprintf
    fprintf('\nFrom NIST data, the coefficient A_N = %f\n',coefficients.A_N)
    
    % Usage in calculation (just use it as if it was a variable/constant name
    AN2 = coefficients.A_N^2 ;
    fprintf('\nA_N coefficient squared = %.2f\n',AN2)
    
    % If you want a shorter notation, you can copy the coefficient value in
    % a variable with a shorter name, then use that variable later in code
    A_N = coefficients.A_N ;
    
    fprintf('\nA_N coefficient cubed = %.2f\n',A_N^3)

end

然后 运行 这个文件(从命令行调用它)产生:

>> Gas
The A_N coefficient taken from NIST data is:
                  28.98641

From NIST data, the coefficient A_N = 28.986410

A_N coefficient squared = 840.21

A_N coefficient cubed = 24354.73

或者如果您只需要在 Matlab 控制台中访问系数:

>> coefficients.A_N
ans =
                  28.98641

现在所有这些示例都假定 class 文件 coefficient.m 在当前 Matlab 范围内可见。对于 Matlab,这意味着该文件必须 在 MATLAB 搜索路径 中(或者当前文件夹也可以)。

有关什么是 Matlab 搜索路径及其工作原理的更多信息,您可以阅读:


在你的情况下,我会创建一个包含所有这些类型的文件夹 classes,然后将这个文件夹添加到 Matlab 路径,这样你就不必再担心单个脚本、函数或程序调用为此。