1、设计一个名为cal的函数,其接受三个参数,第一个参数为操作符,可选的操作符为+、-、*和/,第二和第三个参数为操作数,实现操作符对应的两个操作数双目运算。要求: 1、操作符只能为+、-、*和/ 2、操作数只能为数字 3、为程序添加必要的说明,以增加其可读性 4、建议使用validateattributes校验输入特性 5、查看validateattributes函数的帮助文档,总结其主要用法
时间: 2023-07-10 14:06:43 浏览: 64
以下是实现要求的函数cal:
```matlab
function result = cal(operator, operand1, operand2)
% CAL 实现操作符对应的两个操作数双目运算
% operator: 操作符,只能为+、-、*和/
% operand1: 操作数,只能为数字
% operand2: 操作数,只能为数字
% result: 双目运算结果
% 校验输入特性
validateattributes(operator, {'char'}, {'nonempty'}, 'cal', 'operator');
validateattributes(operand1, {'numeric'}, {'scalar', 'finite'}, 'cal', 'operand1');
validateattributes(operand2, {'numeric'}, {'scalar', 'finite'}, 'cal', 'operand2');
% 根据操作符进行操作数双目运算
switch operator
case '+'
result = operand1 + operand2;
case '-'
result = operand1 - operand2;
case '*'
result = operand1 * operand2;
case '/'
result = operand1 / operand2;
otherwise
error('Unsupported operator!');
end
end
```
validateattributes函数是MATLAB中用于校验输入参数的函数。它可以检查输入参数的类型、大小、范围等特性是否符合要求,并在不符合要求时抛出异常。其主要用法如下:
validateattributes(value, classes, attributes, function_name, parameter_name)
其中,value为待校验的值,classes为允许的类型,可以是一个字符串、一个单元格数组或一个元胞数组,attributes为允许的属性,也可以是一个字符串、一个单元格数组或一个元胞数组,function_name为包含validateattributes函数的函数名,parameter_name为待校验的参数名。其中,value、classes和attributes是必须输入的参数,function_name和parameter_name可以省略。
例如,在本题的函数cal中,validateattributes函数的用法为:
validateattributes(operator, {'char'}, {'nonempty'}, 'cal', 'operator');
其中,operator为待校验的值,{'char'}表示允许的类型为字符型,{'nonempty'}表示不允许为空。