编写一个M函数文件,完成以下功能:没有输入量(输入量为0)或输入量大于2时,给出“出错提示”(disp('input parameter error! Please try again.');输入量等于1时,输出结果为输入量的平方;输入量等于2时,输出结果为第一输入量的第二输入量次方。
提示:输入量的个数使用nargin指令。
该任务的目的:掌握输入量数目的统计指令nargin的用法,nargout的用法类似;
掌握switch—case—end控制流的使用方法;
会根据函数的定义形式调用函数得到正确的运算结果;
会使用句柄对函数进行调用得到正确的运算结果。
(1)函数文件程序框架如下,请填写补充:
创建一个M函数文件:
function y = fexam602(x,n)
% function name: fexam602.m
% result: y = x.^n, default n = 2.
if nargin ~= 2 % 输入量为0或大于2时,报错
disp('input parameter error! Please try again.')
else
switch nargin
case 1
y = x.^2;
disp('The result is ')
disp(y)
case 2
y = x.^n;
disp('The result is ')
disp(y)
end
end
(2)在命令窗口输入命令,直接调用fexam602.m计算:
,
请写出调用语句。
调用语句:fexam602(45,2)
或 fexam602(5,4)
fexam602(45,2)
The result is
2025
ans =
2025
fexam602(5,4)
The result is
625
ans =
625
(3)为函数fexam602创建函数句柄H1,并通过句柄H1实现对函数fexam602的调用,计算
。
创建函数句柄并使用:
H1 = @fexam602;
sum = H1(5,4);
The result is
625