MATLAB - 函数参数
MATLAB - 现代函数参数
Section titled “MATLAB - 现代函数参数”函数是构建健壮且可重用代码的基础。它们通过**输入参数(input arguments)接收数据,并通过输出参数(output arguments)**返回结果。现代 MATLAB 提供了强大而灵活的方式来定义和验证这些参数,使您的代码更可靠、更易于使用且具有自文档性。
MATLAB 函数的结构
Section titled “MATLAB 函数的结构”让我们从基本语法开始:
function [output1, output2] = functionName(input1, input2) % 函数的帮助文本(功能、输入、输出) % 当您输入 'help functionName' 时会显示此文本
% 函数体:使用输入执行计算 output1 = input1 * 2; output2 = input2 + 5;endfunction:开始函数定义的关键字。[output1, output2]:用方括号括起来的逗号分隔的输出参数列表。functionName:您的函数名称。这必须与文件名匹配(例如,functionName.m)。(input1, input2):用逗号分隔的必需输入参数列表。end:终止函数的关键字。
现代方法:arguments 块
Section titled “现代方法:arguments 块”arguments 块(在 R2019b 中引入)是定义函数输入的推荐最佳实践。它允许您声明参数名称、指定其大小和类、设置默认值,以及添加自定义验证规则,所有这些都集中在一个清晰、声明性的块中。
function result = functionName(posArg1, posArg2) arguments posArg1 (1,1) double {mustBeNumeric} % 位置参数 posArg2 (1,:) char {mustBeMember(posArg2, ['A','B'])}
% 名称-值参数 options.PlotStyle (1,1) string = "-" options.LineWidth (1,1) double {mustBePositive} = 1 end % ... 函数体 ...end让我们分解这个语法:
(1,1) double:一个验证,要求posArg1必须是double类型的 1x1 标量。{mustBeNumeric}:一个验证函数。MATLAB 提供了许多(例如,mustBePositive、mustBeInteger),您也可以编写自己的。options.PlotStyle (1,1) string = "-":这定义了一个可选的**名称-值(Name-Value)**参数。如果用户未提供PlotStyle,它将默认为"-"。
实用示例:高级数据绘图函数
Section titled “实用示例:高级数据绘图函数”让我们创建一个健壮的函数 plotData.m,它绘制向量 y 对可选向量 x 的曲线。它还将接受名称-值对来定制绘图。
function plotHandle = plotData(y, x, options)% PLOTDATA 绘制向量 y,并提供广泛的自定义选项。% plotHandle = PLOTDATA(y) 绘制 y 中的数据。% plotHandle = PLOTDATA(y, x) 绘制 y 对 x 的曲线。% plotHandle = PLOTDATA(___, Name, Value) 使用一个或多个名称-值对参数指定绘图选项。
arguments % 位置参数 y (1,:) double {mustBeReal, mustBeFinite} % y 是一个必需的 1xN 向量 x (1,:) double {mustBeReal, mustBeFinite} = 1:length(y) % x 是可选的,默认为 1, 2, 3...
% 'options' 结构体中的名称-值参数 options.LineColor (1,1) string = "blue" % 绘图颜色 options.LineWidth (1,1) double {mustBePositive} = 1.5 % 线条粗细 options.Marker (1,1) string = "o" % 标记样式 options.TitleText (1,1) string = "My Data Plot" % 绘图标题 end
% 输入验证:确保 x 和 y 具有相同数量的元素 if length(x) ~= length(y) error('Inputs x and y must have the same number of elements.'); end
% --- 函数体 --- figure; % 创建一个新的图窗窗口 plotHandle = plot(x, y, ... 'Color', options.LineColor, ... 'LineWidth', options.LineWidth, ... 'Marker', options.Marker, ... 'LineStyle', '-');
grid on; title(options.TitleText); xlabel('X-axis'); ylabel('Y-axis'); legend('Data Series');
end现在您可以从命令行窗口以各种方式调用此函数:
% 生成一些示例数据sampleData = [10 15 13 18 20];
% 1. 简单调用(x 使用默认值)plotData(sampleData);
% 2. 提供自定义 x 轴值timeStamps = [0 0.1 0.2 0.3 0.4];plotData(sampleData, timeStamps);
% 3. 使用名称-值对进行完全自定义plotData(sampleData, timeStamps, LineColor="red", TitleText="Sensor Readings", LineWidth=2);旧版方法:varargin 和 nargin
Section titled “旧版方法:varargin 和 nargin”在 arguments 块出现之前,处理可选参数和名称-值参数需要手动解析 varargin(一个可变输入参数的单元数组)和检查 nargin(输入参数的数量)。虽然您仍然会在旧代码中看到这种情况,但对于新代码,arguments 块更优越,因为它不易出错且可读性更强。