先看下面的代码
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.
明显第三种写法运算速度快得多。所以能向量化运算的尽量向量化,最好少用循环结构。
本文通过三种不同的Matlab代码实现方式对比展示了向量化运算相较于循环结构在效率上的显著优势。实验结果显示,直接使用Matlab内置函数进行向量化操作的速度远超传统循环迭代方法。
8517

被折叠的 条评论
为什么被折叠?



