A little question of [] and for loop

1 次查看(过去 30 天)
Wei Ting Lin
Wei Ting Lin 2021-2-27
回答: Jan 2021-2-27
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?

回答(3 个)

Hernia Baby
Hernia Baby 2021-2-27
It is same as horzcat.
A = 0;
for i=1:50
A=horzcat(A,i);
end
  3 个评论
Hernia Baby
Hernia Baby 2021-2-27
编辑:Hernia Baby 2021-2-27
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
Star Strider 2021-2-27
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.

Jan
Jan 2021-2-27
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.

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by