A little question of [] and for loop

1 visualización (últimos 30 días)
Wei Ting Lin
Wei Ting Lin el 27 de Feb. de 2021
Respondida: Jan el 27 de Feb. de 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?

Respuestas (3)

Hernia Baby
Hernia Baby el 27 de Feb. de 2021
It is same as horzcat.
A = 0;
for i=1:50
A=horzcat(A,i);
end
  3 comentarios
Wei Ting Lin
Wei Ting Lin el 27 de Feb. de 2021
thanks a lots
Hernia Baby
Hernia Baby el 27 de Feb. de 2021
Editada: Hernia Baby el 27 de Feb. de 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

Iniciar sesión para comentar.


Star Strider
Star Strider el 27 de Feb. de 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.
  2 comentarios
Wei Ting Lin
Wei Ting Lin el 27 de Feb. de 2021
thanks!!
Star Strider
Star Strider el 27 de Feb. de 2021
My pleasure!

Iniciar sesión para comentar.


Jan
Jan el 27 de Feb. de 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.

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by