先看下面的代码
function TestTime()
clear;
clc;
t=0:0.01:3*pi;
%第一种写法
disp('******1');
tic;
for i=1:length(t)
y1(i)=sin(t(i));
end
toc;
%第二种写法
disp('******2');
tic;
l=length(t);
y2=zeros(l);
for i=1:l
y2(i)=sin(t(i));
end
%第三种写法
toc;
disp('******3');
tic;
y3=sin(t);
toc;
end
运行的结果如下:
******1
Elapsed time is 0.005446 seconds.
******2
Elapsed time is 0.013515 seconds.
******3
Elapsed time is 0.000162 seconds.
明显第三种写法运算速度快得多。所以能向量化运算的尽量向量化,最好少用循环结构。