else
plot(x(i),y(i),'xr') end end hold off
在搜索路径之下,保存为li6_15.m,在命令窗口键入li6_15,即可得到相应的结果。
3210-1-2-30102030405060708090100
图6.3
【例6.16】:建立M函数文件,画出下列分段函数所表示的曲面。
?0.5457e??y2?6x2f(x,y)??0.7575e?0.5457e?0.75y2?3.75x2?1.5x?在M程序窗口编写如下程序: function qumian(a,b) clf;clc;
x=-a:0.2:a;y=-b:0.2:b; for i=1:length(y) for j=1:length(x) if x(j)+y(i)>1
z(i,j)=0.5457*exp(-0.75*y(i)^2-3.75*x(j)^2-1.5*x(j));
?0.75y2?3.75x2?1.5xx?y?1?1?x?y?1
x?y??1
elseif x(j)+y(i)<=-1
z(i,j)= 0.5457*exp(-0.75*y(i)^2-3.75*x(j)^2+1.5*x(j));
else
z(i,j)=0.7575*exp(-y(i)^2-6*x(j)^2); end end end
colormap(flipud(winter)); surf(x,y,z);
在搜索路径之下,保存为qumian.m,在命令窗口调用qumian(x,y),即可得到相应的结果。 【例6.17】当有更多种选择时,可采用如下的命令格式:
if rand(1)<0.2
disp('rand(1)<0.2') elseif rand(1)<0.4&rand(1)>=0.2 disp('0.2= disp('0.8= 把以上命名保存在搜索路径之下,命名为li6_17。然后在窗口输入: >> li6_17 0.4= switch-case语句的格式是: switch num case n1 command_1 command_2 command_3 ? case n2 case n3 otherwise end command_n switch-case语句的的功能是:一旦参数“num”为其中的某个值或字符串时(如n1或n2或n3,等等),就执行所对应的指令(如commnad_1或command_2或command_3,等等);没有对应时,则执行otherwise后的语句(command_n)。 【例6.18】:某商场对顾客所购买的商品实行打折销售,标准如下: Price<200 无折扣; 200<=price<500 4% 500<=price<1200 8%;1200<=price<3000 12%; 3000<=price<8000 15%;5000<=price 20% 解答: 在M程序窗口编写如下程序: price=input('请输入商品价格:') switch fix(price/100) case {0,1} rate=0; case {2,3,4} rate=4/100; case num2cell(5:11) rate=8/100; case num2cell(12:29) rate=12/100; case num2cell(30:79) rate=15/100; otherwise rate=20/100; end price=price*(1-rate) 在搜索路径之下,保存为li6_18.m,在命令窗口键入li6_18,即可得到相应的结果。 >> li6_18 请输入商品价格:10000 price = 10000 price = 8000 6.2.2 其它语句 1 输入语句 如果要输入数值,采用以下格式: x=input('please input a number:') please input a number:22 x = 22 如果要输入字符串 ,采用以下格式: x=input('please input a string:','s') please input a string:this is a string x = this is a string 2 输出语句 自由格式 (disp): disp(23+454-29*4) 361 disp([11 22 33; 44 55 66; 77 88 99]) 11 22 33 44 55 66 77 88 99 disp('this is a string') this is a string 3 注释语句 注释语句的一般格式是: % 注释文字 注释语句的功能是, 对程序中的语句做必要的说明。 注释语句紧跟在被说明语句之后;文字应尽可能中肯、简单、扼要,避免与其它注释相矛盾。 如在命令窗口输入:edit sqrt,回车后即可得到关于sqrt()函数的解释语句如下: %SQRT Square root. % SQRT(X) is the square root of the elements of X. Complex % results are produced if X is not positive. % % See also SQRTM, REALSQRT, HYPOT. % Copyright 1984-2005 The MathWorks, Inc. % $Revision: 5.7.4.5 $ $Date: 2005/04/28 19:53:41 $ % Built-in function. 4 中断语句