文档下载 文档下载导航
设为首页 | 加入收藏
搜索 请输入内容:  
 导航当前位置: 文档下载 > 所有分类 > 高等教育 > 工学 > Stephen J.Chapman《MATLAB 编程(第二版) 》第四章
侵权投诉

Stephen J.Chapman《MATLAB 编程(第二版) 》第四章

Stephen J.Chapman《MATLAB 编程(第二版) 》第四章

我们的错误就在于我们没有检测程序所有可能的输入类型。请重看一遍程序。如果我们不输入数或者只输入一个数,那么上面的公式就会出现除以0的情况。这种除0错误将会在导致在命令窗口内出现divide-by-zero的警告,导致输出值为无穷大(NaN)。我们需要修改这个程序来解决这个问题,告诉用户这个问题是什么,并在适当的时侯停止。这个程序的修定版本为stats_2。在运行运算之前,我们必须检查是否有足够多的输入值。如果没有,程序将打印出错误提示信息,并且跳出。你自己检测一下这个版本的程序。

% Script file: stats_2.m %

% Purpose:

% To calculate mean and the standard deviation of % an input data set containing an arbitrary number % of input values. %

% Record of revisions:

% Date Programmer Description of change

% ==== ========== ===================== % 12/05/97 S. J. Chapman Original code

% 1. 12/06/97 S. J. Chapman Correct divide-by-0 error if % 0 or 1 input values given. %

% Define variables:

% n -- The number of input samples

% std_dev -- The standard deviation of the input samples % sum_x -- The sum of the input values

% sum_x2 -- The sum of the squares of the input values % x -- An input data value

% xbar -- The average of the input samples % Initialize sums.

n = 0; sum_x = 0; sum_x2 = 0; % Read in first value

x = 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: '); end

% 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); end

注意平均数和标准差可以通过MATLAB的内建函数mean和std计算得到,输入数据存储在一个向量内,并把向量作为函数的参数。在本章章末的练习中,将会要求你用标准的matlab函数创建一个新的版本程序。

上一页第5页

你可能喜欢

热门文档

相关文档

站点地图 | 文档上传 | 侵权投诉 | 手机版
本站所有资源均来自互联网,本站只负责收集和整理,均不承担任何法律责任,如有侵权等其它行为请联系我们.
文档下载 Copyright 2013 doc.guandang.net All Rights Reserved.  -  email