Matlab for loop is actually not slow

Source: Internet
Author: User

Matlab for loop is not slow, first of all Matlab is an interpretation of the implementation of the language, variables do not need to be declared in advance, which is causing many people mistakenly think that Matlab for loop is very slow. In fact, it is wrong to know.

Cause: Because the variables in the MATLAB loop are not pre-declared, the size of the array changes in the loop, and when the size grows, the current array may need to be copied into the new larger contiguous memory, which obviously leads to unnecessary overhead. If the length of the array is shorter, the number of copies that occur is less, and the content that needs to be copied is short, so the deceleration is less obvious. If it is very long, it is not difficult to imagine, but also can think of if the pre-declaration of a large enough array can avoid this process.


The above is a reference to the following:

http://www.zhihu.com/question/33193085


The results of your own tests:

# Cat TMP1.M

Clear all; CLC

Tic
a = [];
For i = 1:200,000
A (i) = i + 1;
% A = [a i + 1];
End
ToC

Running TMP1.M, time-consuming 0.079107 seconds.


# Cat TMP2.M

Clear all; CLC

Tic
a = [];
For i = 1:200,000
% A (i) = i + 1;
A = [a i + 1];
End
ToC Running TMP2.M, time-consuming 20.464098 seconds.


From the above comparison, it can be seen that the MATLAB for loop is time consuming, or because of the statement time that the for loop memory executes. TMP2.M is time-consuming because the a matrix requires a large enough contiguous memory to be applied to the system, and the copying of data can occur, so it is time consuming.

Finally, it can be seen that TMP1.M is a solution for TMP2.M.


Welcome to leave a message to discuss.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.