6.1 数据的保存和读取2+单一输出变量的函数1+函数的向量化
6.1.1. 数据读取及练习
练习
%从文件里加载数据到矩阵中 load后会生成以文件名命名的矩阵 load salesfigs.dat %分离矩阵到两个部分 asales=salesfigs(1,:); bsales=salesfigs(2,:); %画图 plot(asales,'ko'); %黑色的圆圈 hold on; plot(bsales,'k*'); %黑色的星 xlabel('Quarter'); ylabel('Sales (billions)'); title('ABC Corporation Sales: 2013'); legend('Division A','Division B');
6.1.2 函数
%function outputArgument=functionname(inputArgument) %outputArgument是输出变量的名字,functionname函数的名字,inputArgument是输入变量的名字 %文件名要和函数名一致 function area = calcarea(rad) area =pi*rad.^2; end
6.2 单一输出变量的函数1+变量使用范围+子函数
3:49-5:33
在脚本中使用函数
radius=5; fprintf('The circle of radius %f has an area of %f.\n',radius,calcarea(radius));
%% 计算圆锥的函数 V=1/3*SH function vol=conevol(radius,height) vol=pi * radius.^2 .* height / 3; end %%命令行窗口 >> conevol(4,6.1) ans = 102.2065 >> conevol([1 2],[2 1]) ans = 2.0944 4.1888
function OutCost=cylinderCost(radius,height,cost) %圆柱 计算表面积:侧面和两个底 surf_area=2 * pi * radius * height + 2 * pi * radius .^2; %计算花费 OutCost = surf_area * cost; end %%命令行窗口 >> Tcost=cylinderCost(2,3,1.5) Tcost = 94.2478
函数调用的重点
如果函数存放在和文件名相同的文件下,会成为公共函数,能在命令行窗口调用。如果函数跟在其它内容的后面,就成为了一个局部函数,只能在同一个脚本中使用,命令行窗口不能调用
6.3 if判断语句
%提示用户输入一个数字且求它的平方根 num = input('Please enter a number:'); if num < 0 disp('OK,we will use the absolute value'); num=abs(num); end fprintf('The sqrt of %f is %f.\n',num,sqrt(num)); %% 命令行窗口 >> sqrtifexamp Please enter a number:-4 OK,we will use the absolute value The sqrt of 4.000000 is 2.000000. >> sqrtifexamp Please enter a number:4 The sqrt of 4.000000 is 2.000000.