
本科数模培训-matlab2(wyy).ppt
40页第二部分第二部分 程序基本流程程序基本流程Matlab 8/17/202411 关系运算符和逻辑运算符n n运算符 运算== == 等于等于~= ~= 不等于不等于> > 大于大于>= >= 大于或等于大于或等于< < 小于小于<= <= 小于或等于小于或等于8/17/20242n n逻辑运算符& & 逻辑与逻辑与| | 逻辑或逻辑或xorxor 逻辑与或逻辑与或~ ~ 逻辑非逻辑非8/17/202438/17/202442 选择结构(分支语句)选择结构的语句有选择结构的语句有if if语句和语句和switchswitch语句1.. if语句语句 格式一:格式一: if if 条件条件 语句组语句组 endend格式二:格式二: if if 条件条件 语句组语句组1 1 else else 语句组语句组2 2 end end8/17/20245【【【【例例例例】】】】 输入三角形的三条边,求面积。
输入三角形的三条边,求面积输入三角形的三条边,求面积输入三角形的三条边,求面积 A=input('A=input('请输入三角形的三条边:请输入三角形的三条边:');'); if A(1)+A(2)>A(3) & A(1)+A(3)>A(2) & A(2)+A(3)>A(1) if A(1)+A(2)>A(3) & A(1)+A(3)>A(2) & A(2)+A(3)>A(1) p=(A(1)+A(2)+A(3))/2; p=(A(1)+A(2)+A(3))/2; s= s=sqrt(psqrt(p*(p-A(1))*(p-A(2))*(p-A(3)));*(p-A(1))*(p-A(2))*(p-A(3))); disp(sdisp(s); ); else else dispdisp(' ('不能构成一个三角形不能构成一个三角形') ') end end运行:运行: 请输入三角形的三条边:请输入三角形的三条边:[4 5 6][4 5 6] 9.9216 9.92168/17/20246disp ('This program solves for the roots of a quadratic ');disp ('equation of the form A*X^2 + B*X + C = 0.');a = input('Enter the coefficient A: ');b = input('Enter the coefficient B: ');c = input('Enter the coefficient C: ');% Calculate discriminantdiscriminant = b^2 - 4 * a * c;if discriminant > 0 % there are two real roots, so ... x1 = (-b + sqrt(discriminant)) / (2*a); x2 = (-b - sqrt(discriminant)) / (2*a);【【【【例例例例】】】】设计并编写一个程序,用来求解一元二次方程的根。
8/17/20247 disp('This equation has two real roots:'); fprintf('x1 = %f\n', x1); fprintf('x2 = %f\n', x2);else if discriminant == 0 % there is one repeated root, so ... x1 = ( -b ) / (2*a); disp('This equation has two identical real roots:'); fprintf('x1 = x2 = %f\n', x1); else % there are complex roots, so ... real_part = (-b) / (2*a); imag_part = sqrt( abs(discriminant)) / (2*a); disp('This equation has complex roots:'); fprintf('x1 = %f + i %f \n',real_part, imag_part); fprintf('x2 = %f - i %f \n', real_part, imag_part);end8/17/202482..switch语句语句 switchswitch语句根据表达式的取值不同,分别执行语句根据表达式的取值不同,分别执行语句根据表达式的取值不同,分别执行语句根据表达式的取值不同,分别执行不同的语句,其语句格式为:不同的语句,其语句格式为:不同的语句,其语句格式为:不同的语句,其语句格式为:8/17/20249【【例例】】某商场对顾客所购买的商品实行打折销某商场对顾客所购买的商品实行打折销售,标准如下售,标准如下(商品价格用商品价格用price来表示来表示):: price<200 没有折扣没有折扣 200≤price<500 3%折扣折扣 500≤price<1000 5%折扣折扣 1000≤price<2500 8%折扣折扣 2500≤price<5000 10%折扣折扣5000≤price 14%折扣折扣输入所售商品的价格,求其实际销售价格。
输入所售商品的价格,求其实际销售价格8/17/202410 程序如下:程序如下:程序如下:程序如下:price=input('price=input('请输入商品价格请输入商品价格请输入商品价格请输入商品价格');');switch fix(price/100) switch fix(price/100) case {0,1} % case {0,1} %价格小于价格小于价格小于价格小于200200 rate=0; rate=0; case {2,3,4} % case {2,3,4} %价格大于等于价格大于等于价格大于等于价格大于等于200200但小于但小于但小于但小于500500 rate=3/100; rate=3/100; case num2cell(5:9) % case num2cell(5:9) %价格大于等于价格大于等于价格大于等于价格大于等于500500但小于但小于但小于但小于10001000 rate=5/100; rate=5/100; case num2cell(10:24) % case num2cell(10:24) %价格大于等于价格大于等于价格大于等于价格大于等于10001000但小于但小于但小于但小于25002500 rate=8/100; rate=8/100; case num2cell(25:49) % case num2cell(25:49) %价格大于等于价格大于等于价格大于等于价格大于等于25002500但小于但小于但小于但小于50005000 rate=10/100; rate=10/100; otherwise % otherwise %价格大于等于价格大于等于价格大于等于价格大于等于50005000 rate=14/100; rate=14/100;endendprice=price=priceprice*(1-rate) %*(1-rate) %输出商品实际销售价格输出商品实际销售价格输出商品实际销售价格输出商品实际销售价格8/17/202411while语句的一般格式为:语句的一般格式为: while (条件条件) 循环体语句循环体语句 end 其执行过程为:若条件成立,则执行循环体其执行过程为:若条件成立,则执行循环体语句,执行后再判断条件是否成立,如果语句,执行后再判断条件是否成立,如果不成立则跳出循环。
不成立则跳出循环3 while 循环8/17/202412例:统计问题n一组数据的平均数(数学期望)和标准差平均数的定义如下:n其中xi 代表n 个样本中的第i 个样本如果所有的输入数据都可以在一个数组中得到,这些数据的平均数就可以通过公式(4.1)直接计算出来,或应用MATLAB 的内建函数meann标准差的定义如下:8/17/202413% Initialize sums.n = 0; sum_x = 0; sum_x2 = 0;% Read in first valuex = input('Enter first value: ');% While Loop to read input values.while x >= 0 % Accumulate sums. n = n + 1; sum_x = sum_x + x; sum_x2 = sum_x2 + x^2; % Read in next value x = input('Enter next value: ');end8/17/202414% Check to see if we have enough input data.if n < 2 % Insufficient information disp('At least 2 values must be entered!');else % There is enough information, so % calculate the mean and standard deviation x_bar = sum_x / n; std_dev = sqrt( (n * sum_x2 - sum_x^2) / (n * (n-1)) ); % Tell user. fprintf('The mean of this data set is: %f\n', x_bar); fprintf('The standard deviation is: %f\n', std_dev); fprintf('The number of data points is: %f\n', n);end8/17/202415for语句的格式为:语句的格式为:for 循环变量循环变量=表达式表达式1:表达式表达式2:表达式表达式3 循环体语句循环体语句 end 其中表达式其中表达式其中表达式其中表达式1 1的值为循环变量的初值,表达式的值为循环变量的初值,表达式的值为循环变量的初值,表达式的值为循环变量的初值,表达式2 2的值为步长,表达式的值为步长,表达式的值为步长,表达式的值为步长,表达式3 3的值为循环变量的终值。
的值为循环变量的终值的值为循环变量的终值的值为循环变量的终值步长为步长为步长为步长为1 1时,表达式时,表达式时,表达式时,表达式2 2可以省略可以省略可以省略可以省略4 for 循环8/17/2024168/17/2024178/17/202418例: 计算the day of year% Get day, month, and year to convertdisp('This program calculates the day of year given the ');disp('current date.');month = input('Enter current month (1-12):');day = input('Enter current day(1-31):');year = input('Enter current year(yyyy): ');% Check for leap year, and add extra day if necessaryif mod(year,400) == 0 leap_day = 1; % Years divisible by 400 are leap yearselseif mod(year,100) == 0 leap_day = 0; % Other centuries are not leap yearselseif mod(year,4) == 0 leap_day = 1; % Otherwise every 4th year is a leap yearelseleap_day = 0; % Other years are not leap yearsend8/17/202419% Calculate day of year by adding current day to the% days in previous months.day_of_year = day;for ii = 1:month - 1 % Add days in months from January to last month switch (ii) case {1,3,5,7,8,10,12}, day_of_year = day_of_year + 31; case {4,6,9,11}, day_of_year = day_of_year + 30; case 2, day_of_year = day_of_year + 28 + leap_day; endend% Tell userfprintf('The date %2d/%2d/%4d is day of year %d.\n', ... month, day, year, day_of_year);8/17/2024205 break语句和continue语句n n break语句用于终止循环的执行。
当在循环语句用于终止循环的执行当在循环体内执行到该语句时,程序将跳出循环,体内执行到该语句时,程序将跳出循环,继续执行循环语句的下一语句继续执行循环语句的下一语句n ncontinue语句控制跳过循环体中的某些语句语句控制跳过循环体中的某些语句当在循环体内执行到该语句时,程序将跳当在循环体内执行到该语句时,程序将跳过循环体中所有剩下的语句,继续下一次过循环体中所有剩下的语句,继续下一次循环8/17/202421例例 求求[100,,200]之间第一个能被之间第一个能被21整除的整整除的整数程序如下:程序如下:for n=100:200 if rem(n,21)~=0 continue end breakendn8/17/2024226 循环的嵌套n n如果一个循环结构的循环体又包括一个循如果一个循环结构的循环体又包括一个循环结构,就称为循环的嵌套,或称为多重环结构,就称为循环的嵌套,或称为多重循环结构循环结构8/17/202423例:例:例:例: 若一个数等于它的各个真因子之和,则称该数若一个数等于它的各个真因子之和,则称该数若一个数等于它的各个真因子之和,则称该数若一个数等于它的各个真因子之和,则称该数为完数,如为完数,如为完数,如为完数,如6=1+2+36=1+2+3,所以,所以,所以,所以6 6是完数。
求是完数求是完数求是完数求[1,500][1,500]之间的全部完数之间的全部完数之间的全部完数之间的全部完数for m=1:500for m=1:500 s=0; s=0; for k=1:m/2 for k=1:m/2 if if rem(m,krem(m,k)==0)==0 s= s=s+ks+k; ; end end end end if m==s if m==s disp(mdisp(m); ); end endendend8/17/2024248 逻辑数组与向量化n n“逻辑”数据类型在MATLAB 中并不真实存在其实,它是带特定逻辑属性标准数字型数据类型逻辑型数组通过所有的关系运算符和逻辑运算符创建它们区别于数字型的是在调用whos 命令时,(logical)会出现在类型的后面8/17/202425n n当调用whos 命令时,结果如下注意b 后面的(logical)修饰符8/17/202426n n语句c=logical(a),将会把a 值赋于c,从而使c 带有一定的逻辑性。
n n一个数组的逻辑属性可以通任何的数学运算去除例如,如果我们在c 数组加0,数组的值不会改变,而它的逻辑属性将会消失8/17/202427n n逻辑数组的作用n n算术运算中能提供一个屏蔽算术运算中能提供一个屏蔽(mask)(mask)n n屏蔽屏蔽(mask)(mask)是指一个数组,它从另一个数组选是指一个数组,它从另一个数组选择所需的元素参与运算指定的运算只在选择择所需的元素参与运算指定的运算只在选择的元素上执行,而不执行原有的元素的元素上执行,而不执行原有的元素8/17/2024288/17/202429n用循环结构和选择结构计算上述问题n然用逻辑数组的方法运算速度要快得多8/17/202430n n例:用最小二乘法画噪声数据的近似曲线 下落物体将会作匀加速度运动,它的速度符下落物体将会作匀加速度运动,它的速度符合下面的公式合下面的公式 v(t) = at + v0 (4.3)(4.3) v(t)代表物体在代表物体在t 时刻的速度加速度为时刻的速度加速度为g,,初速度初速度v0 为为0。
8/17/202431如果我们确定了待定系数m 和b,那么我们就确定了解析式4.4 y=mx+b (4.4)确定待定系数m 和b 的标准方法为最小二乘法之所以称为最小二乘法,是因为根据偏差的平方和为最小的条件来选择常数m 和b 的公式如下:8/17/202432n n其中,其中,∑ ∑x 代表所有测量值代表所有测量值x 之和,之和,∑ ∑y 代表所有代表所有测量值测量值y 之和,之和,∑ ∑xy 代表所有对应的代表所有对应的x与与y 的乘积的乘积之和,之和, 代表测值量代表测值量x 的数学期望的数学期望 代表测值量代表测值量y 的数学期望已知有一系列含有噪声的数据的数学期望已知有一系列含有噪声的数据( (x,,y) ),编写程序用最小二乘法计算出,编写程序用最小二乘法计算出m 和和b数据要求从键盘输入,画出每一个数据点还有画出最适求从键盘输入,画出每一个数据点还有画出最适合的直线合的直线8/17/202433n n设计算法这个问题被分解为6 个大步骤:Get the number of input data pointsRead the input data valuesCalculate the required statisticsCalculate the slop and interceptWrite out the slop and interceptPlot the input points and the fitted line8/17/202434% Script file: lsqfit.mdisp('This program performs a leastsquares fit of an ');disp('input data set to a straight line.');n_points = input(‘Enter the number of input [x y] points: ');% Read the input datafor ii = 1:n_points temp = input('Enter [x y] pair: '); x(ii) = temp(1); y(ii) = temp(2);end8/17/202435% Accumulate statisticssum_x = 0;sum_y = 0;sum_x2 = 0;sum_xy = 0;for ii = 1:n_points sum_x = sum_x + x(ii); sum_y = sum_y + y(ii); sum_x2 = sum_x2 + x(ii)^2; sum_xy = sum_xy + x(ii) * y(ii);end% Now calculate the slope and intercept.x_bar = sum_x / n_points;y_bar = sum_y / n_points;slope = (sum_xy - sum_x * y_bar) / ( sum_x2 - sum_x * x_bar);y_int = y_bar - slope * x_bar;8/17/202436% Tell user.disp('Regression coefficients for the leastsquares line:');fprintf(' Slope (m) = %8.3f\n', slope);fprintf(' Intercept (b) = %8.3f\n', y_int);fprintf(' No of points = %8d\n', n_points);% Plot the data points as blue circles with no connecting lines.plot(x,y,'bo');hold on;% Create the fitted linexmin = min(x);xmax = max(x);ymin = slope * xmin + y_int;ymax = slope * xmax + y_int;8/17/202437% Plot a solid red line with no markersplot([xmin xmax],[ymin ymax],'r','LineWidth',2);hold off;% Add a title and legendtitle ('\bfLeastSquaresFit');xlabel('\bf\itx');ylabel('\bf\ity');legend('Input data','Fitted line');grid on8/17/202438 作业: 1. 在邮局发一个包裹,不超过两英磅的则收款为10 美元。
超过两英磅每英磅按3.75美元来计费,如果包裹的重量超过了70 英磅,超过了70 英磅的部分,每英磅的价格为1.0美元如果超过了100 英磅则拒绝邮递编写一个程序,输入包裹的重量,输出它的邮费 2. 均方根平均数(rmsaverage)均方根平均数是另一种计算数据平均数的方法它的定义如下 编写一个程序,它能接受任意个数的正输入值,并计算它们的算太平均数和几何平均数用while 循环读取输入值,当输入一个负数中止输入数据计算数列10,5,2,5 的均方根平均数,用以检测程序 8/17/202439 3. 画轨道一颗卫星绕地球运行,卫星的轨道是椭圆形的,而地球就处于这个椭圆的某一个焦点上卫星的轨迹方程满足下式 已知卫星的p=1000km,画出卫星的轨迹 已知(a) ε=0;(b) ε=0.25;(c) ε=0.5 每一颗卫星到地球最近距离是多少?最远距离是多少?比较这三幅图,说出p 代表意义是什么? 4. 4. 病毒的繁殖假设某生物学家做实验,测试一种特殊病毒在不同的培养基下的繁殖速率实验表明A 培养基中的病毒每60 分钟复制一次,A 培养基中的病毒每90 分钟复制一次。
假设在两个培养基中开始的时候各有一个病毒编写一个程序,计算24 小时之内每隔三小时病毒在各自培养基中的个数,并画出图象画两个图,一个用线性坐标,一个用线性对数坐标24 小时之后两培养基中的病毒的数目分别是多少8/17/202440。
