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

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

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

好的编程习惯

那种既可以用向量可以解决的问题,也可以用循环解决的问题,最好用向量解决,这是因为向量执行的速度快。

例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

上一页第12页

你可能喜欢

热门文档

相关文档

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