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