首页 > 解决方案 > Matlab中常数值和相关参数的单独定义

问题描述

在我的代码中,我有很多常量值和参数,它们在我的代码中占用了大量空间。

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

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

一个例子:Coefficients.m如下所示:

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

另一个文件:我想使用的Gas.mA_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

标签: matlabconstantscode-cleanup

解决方案


好的,假设类coefficients定义为:

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

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

然后假设以下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

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

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


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


推荐阅读