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 件のコメント
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 Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by