`
hustlong
  • 浏览: 121177 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

加速matlab运行

阅读更多

一、 遵守Performance Acceleration的规则
二、 遵守三条规则






一、 遵守Performance Acceleration的规则
关于什么是“Performance Acceleration”请参阅matlab的帮助文件。我只简要的将
其规则总结如下7条:1、只有使用以下数据类型,matlab才会对其加速:logical,char,int8,uint8,int16,uint16,int32,uint32,double
而语句中如果使用了非以上的数据类型则不会加速,如:numeric,cell,structure,single,
function handle,java classes,user classes,int64,uint64
2、matlab不会对超过三维的数组进行加速。3、当使用for循环时,只有遵守以下规则才会被加速:a、for循环的范围只用标量值
来表示;
b、for循环内部的每一条语句都要满足上面的两条规则,即只使用支持加速的数
据类型,只使用
三维以下的数组;c、循环内只调用了内建函数(build-in function)。4、当使用if、elseif、while和switch时,其条件测试语句中只使用了标量值时,将
加速运行。
5、不要在一行中写入多条操作,这样会减慢运行速度。即不要有这样的语句:
x = a.name; for k=1:10000, sin(A(k)), end;
6、当某条操作改变了原来变量的数据类型或形状(大小,维数)时将会减慢运行速
度。
7、应该这样使用复常量x = 7 + 2i,而不应该这样使用:x = 7 + 2*i,后者会降低
运行速度。

二、 遵守三条规则
1、尽量避免使用循环,MATLAB的文档中写到“MATLAB is a matrix language, which means it is designed
for vector and matrix operations. You can often speed up your M-file c
ode by using
vectorizing algorithms that take advantage of this design. Vectorizati
on means converting
for and while loops to equivalent vector or matrix operations.”。改进
这样的状况有两种方法:
a、尽量用向量化的运算来代替循环操作。如将下面的程序:
i=0;
for t = 0:.01:10
i = i+1;
y(i) = sin(t);
end
替换为:
t = 0:.01:10;
y = sin(t);
速度将会大大加快。最常用的使用vectorizing技术的函数有:All、diff、ipermute、permute、reshape、squeeze、any、find、logical、prod、shiftdim、sub2ind、cumsum、ind2sub、ndgrid、repmat、sort、sum 等。
请注意matlan文档中还有这样一句补充:“Before taking the time to
vectorize your code, read the section on Performance Acceleration.
You may be able to
speed up your program by just as much using the MATLAB JIT Accelera
tor instead of
vectorizing.”。何去何从,自己把握。
b、在必须使用多重循环时下,如果两个循环执行的次数不同,则在循环的外环执
行循环次数少的,
内环执行循环次数多的。这样可以显著提高速度。
2、a、预分配矩阵空间,即事先确定变量的大小,维数。这一类的函数有zeros、ones、cell、struct、repmat等。
b、当要预分配一个非double型变量时使用repmat函数以加速,如将以下代码:
A = int8(zeros(100));
换成:
A = repmat(int8(0), 100, 100);
c、当需要扩充一个变量的大小、维数时使用repmat函数。
3、a、优先使用matlab内建函数,将耗时的循环编写进MEX-File中以获得加速。b、使用Functions而不是Scripts 。


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics