How to improve computing in matlab?

조회 수: 2 (최근 30일)
C Zeng
C Zeng 2012년 6월 12일
Hi, it is a general question, in my matlab code I used a lot of loops, and inner loops as well. The result is it cannot get a solution quickly.
I was told that VC is good at loop, but matlab is not, matlab is good at matrix computation. And if I used a lot of matrix calculation, choose matlab.
Is there some suggestions? Thank you!

채택된 답변

Sean de Wolski
Sean de Wolski 2012년 6월 12일
MATLAB is fine with loops. It's been fine with loops for a very long time but yet still carries that mantra that "loops are bad". They're not. There are some steps you can take to ensure that loops are running at their finest such as:
  • using functions
  • avoiding eval and evil eval wrappers (like str2num (for all you CODY players gaming the system!))
  • preallocating arrays
  • using integers as loop variables when they are used as an index
  • avoid repeated computations
  • avoid changing the class of a variable if possible
  • etc.
(I'm sure Jan will be able to extend this list 10fold).
Moral of the story is: Don't avoid loops like the plague, avoid the bad things above like the plague.
  댓글 수: 3
Kye Taylor
Kye Taylor 2012년 6월 13일
Well put, Sean
Jan
Jan 2012년 6월 13일
편집: Jan 2012년 10월 27일
@Sean: The list includes the most important strategies already. Some further ideas:
  • Process numerical data columnwise, because accessing the neighboring elements of the memory allows a faster caching. Examples:
X = rand(1e4);
tic; Y = sum(sum(X, 2), 1); toc % 0.19 sec, main work along the rows
tic; Y = sum(sum(X, 1), 2); toc % 0.17 sec, main work along the columns
  • Reduce the number of arithmetic operations when dealing with arrays and scalars:X = rand(1e4); a = 5;Slow: Y = X + pi + 3 + a; This is (((X + pi) + 3) + a) => Three matrix operationsFast: Y = X + (pi + 3 + a); => One matrix operation
  • Use PARFOR to employ more cores.
  • FIND(STRCMP) is much faster than STRMATCH.
  • Do not spend hours for optimizing code until it is so ugly, that you cannot debug it anymore, if it save some seconds of runtime only.
  • Do not let the output of PROFILE confuse you: PROFILE disables the JIT-accelerations, such that Matlab looses its power to process loops efficiently. TIC/TOC is better to measure speed of loops.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

C Zeng
C Zeng 2012년 6월 17일
thanks to all of your help!

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by