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.