A little question of [] and for loop

22 views (last 30 days)
Wei Ting Lin on 27 Feb 2021
Answered: Jan on 27 Feb 2021
for i=1:50
A=[A i];
end
Why this command will make A become 1 2 3 4 5 6 7.....?
What's the reason?

Hernia Baby on 27 Feb 2021
It is same as horzcat.
A = 0;
for i=1:50
A=horzcat(A,i);
end
Hernia Baby on 27 Feb 2021
My pleasure!
When you want to learn the feeling of this algolism, you can use disp following.
A = [];
for i=1:5
A=[A i];
disp(sprintf('Step %i',i));
disp(A);
end
Step 1
1
Step 2
1 2
Step 3
1 2 3
Step 4
1 2 3 4
Step 5
1 2 3 4 5

Star Strider on 27 Feb 2021
The full code should actually be:
A = [];
for i=1:50
A=[A i];
end
It works by concatenating the value of ‘i’ to existing values of ‘A’.
See the ‘square brackets’ documentation in MATLAB Operators and Special Characters for details on these and other special characters.
Star Strider on 27 Feb 2021
My pleasure!

Jan on 27 Feb 2021
By the way, this code is a standard example of a programming style, which wastes ressources.
A = [];
for i=1:50
A=[A i];
end
This let the vector A gro iteratively. In each iteration a new element is appended. For e.g. i=10 a new vector with 10 elements is created, the former 9 values are copied an the next value is inserted. For 50 elements this does not mean a lot of work. But for e.g. 1e6 elements, Matlab does not have to reserve memory for 1e6 elements, but for sum(1:1e6) elements and copy almost the same amount of data. For doubles using 8 Byte per element this is 4 TB. Although all but the final vector is freed, this wastes a lot of time.
The solution is "pre-allocation": Create the vector once with its final size:
tic
A = zeros(1, 1e6);
for i = 1:1e6
A(i) = i;
end
toc
tic
B = [];
for i = 1:1e6
B = [B, i];
end
toc
% Elapsed time is 0.003929 seconds.
% Elapsed time is 0.983451 seconds.
This is the improved runtime, when the code is included in a function. It the JIT-acceleration is disabled, e.g. during debugging or when running the code in the command line, the iterative growing can take minutes.