Can anyone explain for loop ? And nested loops.

2 ビュー (過去 30 日間)
Maulik Brahmane
Maulik Brahmane 2020 年 2 月 18 日
コメント済み: Stephen23 2020 年 2 月 18 日
%Please explain me the for loop , and nested loops.
for

回答 (1 件)

John D'Errico
John D'Errico 2020 年 2 月 18 日
編集済み: John D'Errico 2020 年 2 月 18 日
How can we do better than to suggest you read the help for for? It has examples in there.
help for
doc for
A simple for loop:
N = 5;
X = zeros(1,N); % preallocate X to the final size
for n = 1:N
X(n) = n.^2 + 1;
end
Nested loops:
N = 12;
A = zeros(N,N); % preallocation
for R = 1:N
for C = 1:N
A(R,C) = 1/(R+C-1);
end
end
The loop variable will increment on each pass through the loop, with everything between the for and the corresponding end statement being executed in its normal sequence.
Don't grow arrays dynamically, as that will be the cause of extrememly slow code. Then you will be anxiously asking later how to speed up your code. So use preallocation for arrays and vectors that will be otherwise grown to their final size.
There are many other ways to use loops, both for and while loops. READ THE HELP! The help was put there for you to use it, and was written for you to read.
  1 件のコメント
Stephen23
Stephen23 2020 年 2 月 18 日
The introductory tutorials also show how to use loops:

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by