按Genial说的是这样子的:
>> clear all
tic;s=0;
for i=1:1000000
s=s+i;
end
s
disp('use for');toc
clear all
tic;s=0;i=0;
while i<1000000
s=s+i;
i=i+1;
end
s
disp('use while');toc
clear all
tic;
i=1:1000000;
s=sum(i)
disp('use sum');toc
s =
5.0000e+011
use for
elapsed_time =
1.1870
s =
5.0000e+011
use while
elapsed_time =
3.0780
s =
5.0000e+011
use sum
elapsed_time =
0.0470
◣◣◣◣◣◣去掉代码中间的clear all的执行结果是◥◥◥◥◥◥
s =
5.0000e+011
use for
elapsed_time =
1.2030
s =
5.0000e+011
use while
elapsed_time =
3.0780
s =
5.0000e+011
use sum
elapsed_time =
0.0310
用sum还是比较快。一般书中推荐的优化matlab执行效率时,也包括了向量化执行的方法