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

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

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

数,然后用for循环读取所有数值。

下面的就是这个修定版本的程序。它允许各种输入值,请你自己验证下面5个输入值的平均数和标准差:3,-1,0,1,-2。

% Script file: stats_3.m %

% Purpose:

% To calculate mean and the standard deviation of % an input data set, where each input value can be % positive, negative, or zero. %

% Record of revisions:

% Date Programmer Description of change

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

% Define variables: % ii Loop index

% 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.

sum_x = 0; sum_x2 = 0;

% Get the number of points to input. n = input('Enter number of points: ');

% Check to see if we have enough input data. if n < 2 % Insufficient data

disp ('At least 2 values must be entered.'); else % we will have enough data, so let's get it. % Loop to read input values. for ii = 1:n % Read in next value x = input('Enter value: '); % Accumulate sums. sum_x = sum_x + x; sum_x2 = sum_x2 + x^2; end % Now calculate statistics. 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

4.2.1 运算的细节

既然我们已经看了许多for循环的例子。在用for循环时,我们必须检查许多重要的细节。

1.没有必要缩进for循环的循环体。即使所有语句都左对齐,matlab程序也会识别出这个循环。但缩进循环体能增强代码的可读性,所以建议大家缩进循环体。

好的编程习惯

上一页第10页

你可能喜欢

热门文档

相关文档

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