Matlab中函数文件prime.m的用法
1.函数文件prime.m
function prime(a)
if size(a)~=1|round(a)~=a %判断输入的变量是否为一个整数标量
error('The input argument must be a interger number')
end
for i=2:sqrt(a) %判断a是否能被2到(a-1)之中的任一个数除尽
b=rem(a,i);
if b==0
disp(sprintf('%i is not a prime',a))
break;
end
end
if b~=0 %若循环完后,余数最终还不为零,则此数为素数
disp(sprintf('%i is a prime',a))
end
2.函数文件dele.m
function [remstr,charnum]=dele(a)
%只有ASCII码在32到126之间的整数所对应的符号才能被显示或打印出来,而且该程序只对标量或行、列向量进行操作
for i=1:length(a)
if a(i)<32 | a(i)>126| round(a(i))~=a(i) | any(ismember(size(a),1))==0
error('The input must be an interger array,whose element value is between 32 and 126');
end
end
b=[];
for i=1:length(a)
if a(i)~=32
b=[b,a(i)];
end
end
remstr=char(b);
charnum=length(b);
3.函数文件zeronum.m统计一个数值中的0的个数
function c=zeronum(a)
if size(a)~=1
error('The input argument must be a scalar')
end
b=num2str(a); %提问:为什么要这一步?
c=0;
for i=1:length(b)
if b(i)=='0' %先给不加引号,保存程序后,在命令行用zeronum(700)测试,
%结果为何错误
c=c+1;
end
end
脚本文件zn.m统计1到1999中0的总个数
zn=0;
for i=1:1999
zn=zn+zeronum(i);
end
disp(sprintf('1到1999中0的总个数为%i',zn))
4.函数文件equaroot.m
function equaroot(a,b,c)
%计算一元二次方程y=a*x^2+b*x+c的根,Y=EQUAROOT(A,B,C)
det=b^2-4*a*c
if det>0
y(1)=(-b+sqrt(det))/2*a;
y(2)=(-b-sqrt(det))/2*a;
elseif det==0
y=-b/2*a;
else
y(1)=(-b+i*sqrt(det))/2*a;
y(2)=(-b-i*sqrt(det))/2*a;
end
disp('The roots of the equation are ')
disp(y)
5.函数segfun.m用于计算
function y=segfun(x)
if x>3 | x
error('The input values is between -3 and 3')
end
if x>=-3 & x
c=(-x.^2-4*x-3)/2;
elseif x>=-1 & x<1
c=-x.^2+1;
else
c=(-x.^2+4*x-3)/2;
end
y=c;
脚本文件plotsegfun.m用于画图
a1=[-3:0.01:-1];
plot(a1,segfun(a1),'r.-')
hold on
a2=[-1:0.01:1];
plot(a2,segfun(a2),'b-')
hold on
a3=[1:0.01:3];
plot(a3,segfun(a3),'go')
6.脚本文件menuch.m
ch=menu('请选择参数产生一个3阶方阵','[-10,10]之间均匀分布的随机阵','[-5,5]之间均匀分布的随机阵','[-1,1]之间均匀分布的随机阵','标准正态分布的随机阵')
switch ch
case 1
a= 10-2*10*rand(3)
case 2
a=5-2*5*rand(3)
ca