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函数创建一个新的版本程序。
Stephen J.Chapman《MATLAB 编程(第二版) 》第一章_工学_高等教育_教育专区。Stephen J.Chapman《MATLAB 编程(第二版) 》郑碧波翻译 Matlab 中文论坛首发 http:...
Stephen J.Chapman《MATLAB 编程(第二版) 》第二章Stephen J.Chapman《MATLAB 编程(第二版) 》第二章隐藏>> 郑碧波翻译 Matlab 中文论坛首发 http://www.iLo...
Stephen J.Chapman《MATLAB 编程(第二版) 》第三章Stephen J.Chapman《MATLAB 编程(第二版) 》第三章隐藏>> 郑碧波翻译 Matlab 中文论坛首发 http://www.iLove...
Stephen J.Chapman《MATLAB 编程(第二版) 》第六章Stephen J.Chapman《MATLAB 编程(第二版) 》第六章隐藏>> 郑碧波翻译 Matlab 中文论坛首发 http://www.iLo...
Matlab编程 第四版(Stephen J.Chapman)Quiz部分答案_计算机软件及应用_IT/计算机_专业资料。Matlab编程 第四版 (Stephen J.ChapmanQuiz答案PD...
郑碧波翻译 Matlab 中文论坛首发 http://www.iLoveMatlab.cn 前言 本文为 Stephen J.Chapman《MATLAB 编程(第二版) 》英文影印版的中文译本,这本 书对初学者很...
Chapman 著 邢树军 郑碧波 译 前言郑碧波本文为 Stephen J.Chapman《MATLAB 编程(第二版) 》英文影印版的中文译本,这本 书对初学者很好的入门教材。之前从网...
matlab编程英文版(Stephen J. Chapman )课后答案1_工学_高等教育_教育专区。matlab编程第二版Stephen J. ChapmanMATLAB MATLAB Programming for Enginees Enginees 姓名...
S.J.Chapman《MATLAB编程》中文版修正版_部分7_信息与通信_工程科技_专业资料。...>> cellstring{1} = 'Stephen J. Chapman'; >> cellstring{2} = 'Male'...
S.J.Chapman《MATLAB编程》中文版修正版_部分3_信息与通信_工程科技_专业资料。...Stephen J.Chapman《MAT... 39页 免费 Stephen J.Chapman《MAT... 37页 免...
热门文档