matlab - 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
解决方案
好的,假设类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 路径,这样您就不必再担心单个脚本、函数或程序调用它。
推荐阅读
- android - 在 Android 上的 NavigationButton 中将大小设置为图标
- java - WebClient 请求级别超时抛出称为默认 onErrorDropped 的运算符
- php - 转化上传:如何在每次转化上传时设置转化窗口?
- javascript - 从反应原生组件调用javascript函数
- amazon-web-services - 使用 Terraform 创建 AWS 服务角色
- android - react-native-firebase 自定义声音在 android 8、android 9 上不起作用
- c++ - 在 Windows 中编译 CUDA 的意义
- java - 无法从 Firebase 存储中检索图像的下载 URL(出现异常)[需要紧急帮助]
- javascript - 元素类型无效:应为字符串或类/函数,但得到:未定义
- python - 在单独的单元格上“循环”或“定义”