MATLAB: How to reduce the runtime of a loop with 6000 iterations

loopMATLAB

I want to be able to use a loop for more complex problems with 6000 iterations. This is just an example. I know I can simply use {A = n * 2} to get the answer. I just need to know how to reduce its runtime.
Many thanks!
Z = [];
for n = 1:6000
A = n * 2;
Z = [Z A]
n = n + 1;
end

Best Answer

Um, you can't do so in general. I.e., you can't just magically speed up arbitrary (unspecified) code, for any piece of code. If you could, they would do it automatically for you.
For a specific problem, yes, you might. For the specific example you show, what you wrote was an insanely bad way to write code. (Sorry, but it is. Novices start out writing poor code. We all did at one point.)
1. Growing the array Z in a loop is just a bad idea. This forces MATLAB to re-allocate memory for the variable Z on each iteration, just a bad idea. So there are various ways to solve this problem using a loop that do NOT run slowly. A simple one might be:
Z = 1:6000;
for n = 1:numel(Z)
Z(n) = Z(n)*2;
end
Or, I could have initialized Z as all zeros, then stuffing Z(n) with the element that it must contain.
Z = zeros(1,6000);
for n = 1:numel(Z)
Z(n) = n*2;
end
Either way is adequate, if forced to use a loop here.
2. Incrementing n (the loop variable) inside the for loop is going to cause bugs for you in the near future. You need to learn how to write a for loop, else you will have many problems in the future. Look at the documentation for for. In there, you will never see any example where the loop variable is itself incremented in a FOR loop. The for construct does that for you.
Perhaps you were thinking of a while loop, or some arbitrary loop construct in some other language.
3. Just use
Z = 2*(1:6000);
Or, by appreciating some important (and basic) properties of mathematics:
Z = 2:2:12000;
In either case, no explicit loop is required. As you can see, there is an IMPLICIT loop, created internally by MATLAB. Those colon constructs create a vector of numbers that you never explicitly see. As such, they create internal loops. BUT, those internal implicit loops are MUCH faster to create and work with.
So, the general answer is to understand how MATLAB works as a vector/array language, operating on entire vectors and arrays of numbers, without needing to use explicit loops. Sometimes, loops are necessary, and in fact, they can sometimes be the fastest way to solve a problem.
Related Question