A little question of [] and for loop

조회 수: 6 (최근 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
Wei Ting Lin
Wei Ting Lin 2021년 2월 27일
thanks a lots
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.
  댓글 수: 2
Wei Ting Lin
Wei Ting Lin 2021년 2월 27일
thanks!!
Star Strider
Star Strider 2021년 2월 27일
My pleasure!

댓글을 달려면 로그인하십시오.


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