for循环——有趣例子
例4.5
比较向量算法和循环为了比较循环和向量算法执行若无事所用的时间,用两种方法编程并测试三个运算所花的时间。
1.用for循环计算1到10000的之间每一个整数的平方,而事先不初始化平方数组。
2.用for循环计算1到10000的之间每一个整数的平方,而事先初始化平方数组。
3.用向量算法计算计算1到10000的之间每一个整数的平方。
答案:
这个程序必须用上面提供的三种方示计算出1到10000之间的每一个整数的平方,并测试每一个种算法的时间。测试时间要用到matlab函数tic和toc。tic函数复位内建计时器,而toc函数则从最后一次调用tic以秒开始计时。
因为在许多的计算机中它的时间钟是相当粗略的,所以有必要多运行几次以获得相应的平均数。
下面就是用三种方法编出的matlab
程序。
% Script file: timings.m
%
% Purpose:
% This program calculates the time required to
% calculate the squares of all integers from 1 to
% 10,000 in three different ways:
% 1. Using a for loop with an uninitialized output
% array.
% 2. Using a for loop with an preallocated output
% array.
% 3. Using vectors.
%
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 12/08/97 S. J. Chapman Original code
%
% Define variables:
% ii, jj Loop index
% average1 Average time for calculation 1
% average2 Average time for calculation 2
% average3 Average time for calculation 3
% maxcount Number of times to loop calculation
% square Array of squares
% leap_day Extra day for leap year
% month Month(mm)
% year Year(yyyy)
% Perform calculation with an uninitialized array
% "square". This calculation is done only once
% because it is so slow.
maxcount = 1; % One repetition
tic; % Start timer
for jj = 1:maxcount
clear square % Clear output array
for ii = 1:10000
square(ii) = ii^2; % Calculate square
end
end
average1 = (toc)/maxcount; % Calculate average time
% Perform calculation with a preallocated array
% "square". This calculation is averaged over 10
% loops.
maxcount = 10; % One repetition
tic; % Start timer
for jj = 1:maxcount
clear square % Clear output array
square = zeros(1,10000); % Preinitialize array
for ii = 1:10000
square(ii) = ii^2; % Calculate square
end
end
average2 = (toc)/maxcount; % Calculate average time
% Perform calculation with vectors. This calculation
% averaged over 100 executions.
maxcount = 100; % One repetition
tic; % Start timer
for jj = 1:maxcount
clear square % Clear output array
ii = 1:10000; % Set up vector
square = ii.^2; % Calculate square
end
average3 = (toc)/maxcount; % Calculate average time
% Display results
fprintf('Loop / uninitialized array = %8.4f\n', average1);
fprintf('Loop / initialized array = %8.4f\n', average2);
fprintf('Vectorized = %8.4f\n', average3);
代码格式优美,大家共同学习吧!!!
不错有哦有哟与哦有哦
这个真不错得得
页:
[1]