函数接收图形或轴对象对象作为参数。
我想测试它,如 FIXME
行所示。
为了允许所有有效对象用于exportgraphics
,应该在此处使用哪个测试?
% myexportgraphics.m
function myexportgraphics(f)
arguments
f (1,1) {}; % FIXME add a test here
end
exportgraphics(f,...);
end
最佳答案
此处记录了完整的验证函数列表:
https://uk.mathworks.com/help/matlab/matlab_prog/argument-validation-functions.html
唯一与检查输入类型相关的(除了“double”等特定类型)是mustBeUnderlyingType
您可以在要接受的示例对象上使用 underlyingType
检查哪些类型有效。
underlyingType( figure() ); % 'matlab.ui.Figure'
underlyingType( axes() ); % 'matlab.graphics.axis.Axes'
所以这将检查数字
function myexportgraphics(f)
arguments
f (1,1) {mustBeUnderlyingType(f,'matlab.ui.Figure')};
end
end
但是,这不允许多个变量类型,因此根据 docs你可能想制作自己的验证函数
function myexportgraphics(f)
arguments
f (1,1) {mustBeExportGraphicsType(f)};
end
end
function mustBeExportGraphicsType(g)
if ~ismember( class(g), {'matlab.ui.Figure','matlab.graphics.axis.Axes'} )
eidType = 'mustBeExportGraphicsType:notExportGraphicsType';
msgType = 'Input must be a figure or axes object';
throwAsCaller(MException(eidType,msgType));
end
end
这些是自定义验证函数的要求,重点是我的:
Functions used for validation have these design elements:
- Validation functions do not return outputs or modify program state. The only purpose is to check the validity of the input value.
- Validation functions must accept the value being validated as an input argument. If the function accepts more than one input argument, the first input is the value to be validated.
- Validation functions rely only on the inputs. No other values are available to the function.
- Validation functions throw an error if the validation fails. Using throwAsCaller to throw exceptions avoids showing the validation function itself in the displayed error message.
Creating your own validation function is useful when you want to provide specific validation that is not available using the MATLAB validation functions. You can create a validation function as a local function within the function file or place it on the MATLAB path.
顺便说一句,您可以在自定义验证函数中使用 ishghandle
,它为图形和轴输入返回 true。如果你没有使用 arguments
验证语法,你可以使用 ishghandle
和稍旧的 inputParser
方法来输入验证,或者一个简单的assert
在你的函数开始附近,但这可能超出了这个问题的范围。
关于matlab - 如何在 MATLAB 2022 中测试图形或轴对象的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73644575/