数学建模社区-数学中国

标题: for循环 [打印本页]

作者: 森之张卫东    时间: 2015-9-7 22:40
标题: for循环
for循环

for循环结构是另一种循环结构,它以指定的数目重复地执行特定的语句块。For循环的形式如下
for index = expr



   Statement 1
...          Body
Statement n
end
其中index是循环变量(就是我们所熟知的循环指数),exp是循环控制表达式。变量index读取的是数组expr的行数,然后程序执行循环体(loopbody),所以expr有多少列,循环体就循环多少次。expr经常用捷径表达式的]方式,即first:incr:last。
在for和end之前的语句我们称之为循环体。在for循环运转的过程中,它将被重复的执行。For循环结构函数如下:
1.在for循环开始之时,matlab产生了控制表达式
2.第一次进入循环,程序把表达式的第一列赋值于循环变量index,然后执行循环体内的语句。
3.在循环体的语句被执行后,程序把表达式的下一列赋值于循环变量index,程序将再一次执行循环体语句。
4.只要在控制表达式中还有剩余的列,步骤3将会一遍一遍地重复执行。我们要举大量的例子来说明for循环的操作。

第一,考虑下面的例子
for ii = 1:10
   Statement 1
   ...
   Statement n
end
在这种情况下,控制表达式产生了一个1ⅹ10数组,所以语句1到n将会被重复执行10次。循环系数ii在第一次执行的时侯是1,第二次执行的时侯为2,依次类推,当最后一次执行时,循环指数为10。在第十次执行循环体之后,再也没有新的列赋值给控制表达式,程序将会执行end语句后面的第一句。注意在循环体在最后一次执行后,循环系数将会一直为10。
第二,考虑下面的例子。
for ii = 1:2:10
   Statement 1
   ...
   Statement n
end
在这种情况下,控制表达式产生了一个1ⅹ5数组,所以语句1到n将会执行5次。循环指数ii在第一次执行时为1,第二次执行时为3,依此类推,最后一次执行时为9。在第五次执行循环体之后,再也没有新的列赋值给控制表达式,程序将会执行end语句后面的第一句。注意在循环体在最后一次执行后,循环系数将会一直为9。
第三,考虑下面的例子。
for ii = [5 9 7]
   Statement 1
   ...
   Statementn
end
在这里,控制表达式是一个直接写出的1ⅹ3的数组,所以语句1到n将会执行3次,循环指数ii在第一次执行时为1,第二次执行时为3,第三次执行时为7。循环指数在循环结束之后一直为7。
最后,考虑下面的例子。
for ii = [1 2 3; 4 5 6]
   Statement 1
   ...
   Statement n
end
在这里,控制表达式是一个直接写出的2ⅹ3的数组,所以语句1到n将会执行3次,循环指数ii在第一次执行时为行向量 ,第二次执行时为 ,第三次执行时为 。这个例子说明循环指数可以为向量。
对应于for循环的伪代码为:
for index = expression
   Statement 1
   ...
   Statement n
end
例4.2
阶乘(factorial)函数
为了说明for循环操作,我们将用for循环来计算阶乘函数。阶乘函数的定义如下:
N!=1        N=0
N!=N * (N-1) * (N-2) * ... * 3 * 2 * 1     N>0
计算N的阶乘的matlab代码为
n_factorial = 1
for ii = 1 : n
   n_factorial = n_factorial * ii;
end
假设我们要计算5的阶乘。如果n为5,for循环控制表达式将会产生行向量[1 2 3 4 5]。这种循环将会执行5次,ii值按先后顺序依次为1,2,3,4,5。n_factorial最终的计算结果为1ⅹ2ⅹ3ⅹ4ⅹ5=120。
例4.3
计算the day of year
the day of year是指这一年已经逝去的天数(包括当天)。在平年中,它的取值范围为1到365,在闰年中,它的取值范围1到366。编写一个matlab程序,输入年,月,日,输入为对应的the of year。
答案:
为了确定the day of year,程序需要计算先前月份的天数之后,然后再计算当月已经过去了多少天,在求和的过程中将会用到for循环。因为每一个月的天数不尽相同,所以我们要确定每一个月的正确天数。我们用switch结构来确定它。
在闰年时,在二月后的某一天的the day of year将会比平年时大1。因为在闰年的二月份多出一个2月29号。所以为了正确地计算出the day of year,我们必须确定那一年是闰年。在公历中,闰年是这样规定的
1.能被400整除的年为闰年
2.能被100整除但不能被400整除的年不为闰年
3.能被4整除但不能被100整除年为闰年
4.其余的年份不为闰年
我们将用到mod(求余)函数来确定一个数是否能被另一个数整除。如果函数的返回值为0,则说一个数能被另一个数整除,否则,则不然。
下面是一个用于计算the day of year的程序。注意程序如何计算出前面月份总共的天数,如何应用switch结构确定每一月的天数。
  1. % Script file: doy.m
  2. %
  3. % Purpose:
  4. % This program calculates the day of year corresponding
  5. % to a specified date. It illustrates the use switch
  6. % and for constructs.
  7. %
  8. % Record of revisions:
  9. % Date Programmer Description of change
  10. % ==== ========== =====================
  11. % 12/07/98 S. J. Chapman Original code
  12. %
  13. % Define variables:
  14. % day           --Day (dd)
  15. % day_of_year   --Day of year
  16. % ii            --Loop index
  17. % leap_day      --Extra day for leap year
  18. % month         --Month (mm)
  19. % year          --Year(yyyy)
  20. % Get day, month, and year to convert
  21. disp('This program calculates the day of year given the ');
  22. disp('current date.');
  23. month = input('Enter current month (1-12):');
  24. day = input('Enter current day(1-31):');
  25. year = input('Enter current year(yyyy): ');
  26. % Check for leap year, and add extra day if necessary
  27. if mod(year,400) == 0
  28. leap_day = 1; % Years divisible by 400 are leap years
  29. elseif mod(year,100) == 0
  30. leap_day = 0; % Other centuries are not leap years
  31. elseif mod(year,4) == 0
  32. leap_day = 1; % Otherwise every 4th year is a leap year
  33. else
  34. leap_day = 0; % Other years are not leap years
  35. end
  36. % Calculate day of year by adding current day to the
  37. % days in previous months.
  38. day_of_year = day;
  39. for ii = 1:month - 1
  40. % Add days in months from January to last month
  41. switch (ii)
  42. case {1,3,5,7,8,10,12},
  43. day_of_year = day_of_year + 31;
  44. case {4,6,9,11},
  45. day_of_year = day_of_year + 30;
  46. case 2,
  47. day_of_year = day_of_year + 28 + leap_day;
  48. end
  49. end
  50. % Tell user
  51. fprintf('The date %2d/%2d/%4d is day of year %d.\n', ...
  52.         month, day, year, day_of_year);
复制代码


我们用下面已知的结果来检测这个程序。
1.1999年不是闰年。它的1月1号对应的day of year是1,12月31号必定对应的是365。
2.2000年是一个闰年。它的1月1号对应的day of year是1,12月31号必定对应的是366。
3.2001年不是闰年。它的1月1号对应的day of year是30。这个程序5次运行后的结果分别为
>> doy
This program calculates the day of year given the
current date.
Enter current month (1-12):1
Enter current day(1-31):1
Enter current year(yyyy): 1999

The date  1/ 1/1999 is day of year 1.
>> doy
This program calculates the day of year given the
current date.
Enter current month (1-12):12
Enter current day(1-31):31
Enter current year(yyyy): 1999
The date 12/31/1999 is day of year 365.

>> doy
This program calculates the day of year given the
current date.
Enter current month (1-12):1
Enter current day(1-31):1
Enter current year(yyyy): 2000

The date  1/ 1/2000 is day of year 1.
>> doy
This program calculates the day of year given the
current date.
Enter current month (1-12):12
Enter current day(1-31):31
Enter current year(yyyy): 2000

The date 12/31/2000 is day of year 366.
>> doy
This program calculates the day of year given the
current date.
Enter current month (1-12):3
Enter current day(1-31):1
Enter current year(yyyy): 2001


The date  3/ 1/2001 is day of year 60.
通过5次不同情况的检测,这个程序给出了正确的结果。
例4.4
统计分析
执行如下算法:
输入一系列的测量数,计算它们的平均数和标准差。这些数可以是正数,负数或0。
答案:
这个程序必须能够读取大量数据,并能够计算出这些测量值的平均数和标准差。这些测量值可以是正数,负数或0。
因为我们再也不能用一个数来表示数据中止的标识了,我们要求用户给出输入值的个数,然后用for循环读取所有数值。
下面的就是这个修定版本的程序。它允许各种输入值,请你自己验证下面5个输入值的平均数和标准差:3,­1,0,1,­2。
  1. <font color="black">% Script file: stats_3.m
  2. %
  3. % Purpose:
  4. % To calculate mean and the standard deviation of
  5. % an input data set, where each input value can be
  6. % positive, negative, or zero.
  7. %
  8. % Record of revisions:
  9. % Date Programmer Description of change
  10. % ==== ========== ====================
  11. % 12/08/97 S. J. Chapman Original code
  12. %
  13. % Define variables:
  14. % ii Loop index
  15. % n The number of input samples
  16. % std_dev The standard deviation of the input samples
  17. % sum_x The sum of the input values
  18. % sum_x2 The sum of the squares of the input values
  19. % x An input data value
  20. % xbar The average of the input samples
  21. % Initialize sums.
  22. sum_x = 0; sum_x2 = 0;
  23. % Get the number of points to input.
  24. n = input('Enter number of points: ');
  25. % Check to see if we have enough input data.
  26. if n < 2 % Insufficient data
  27.     disp ('At least 2 values must be entered.');
  28. else % we will have enough data, so let's get it.
  29.     % Loop to read input values.
  30.     for ii = 1:n
  31.         % Read in next value
  32.         x = input('Enter value: ');
  33.         % Accumulate sums.
  34.         sum_x = sum_x + x;
  35.         sum_x2 = sum_x2 + x^2;
  36.     end
  37.     % Now calculate statistics.
  38.     x_bar = sum_x / n;
  39.     std_dev = sqrt((n * sum_x2 - sum_x^2) / (n * (n - 1)));
  40.     % Tell user.
  41.     fprintf('The mean of this data set is: %f\n', x_bar);
  42.     fprintf('The standard deviation is: %f\n', std_dev);
  43.     fprintf('The number of data points is: %f\n', n);
  44. end</font>
复制代码



作者: amirmars    时间: 2015-9-18 16:59
不错,挺有收获





欢迎光临 数学建模社区-数学中国 (http://www.madio.net/) Powered by Discuz! X2.5