1. 程式人生 > >for函式的用法(matlab)

for函式的用法(matlab)

摘自matlab

for Repeat statements a specific number of times. The general form of a for statement is:

   for variable = expr, statement, ..., statement END

The columns of the expression are stored one at a time in
the variable and then the following statements, up to the
END, are executed. The expression is often of the form X:Y,
in which case its columns are simply scalars. Some examples
(assume N has already been assigned a value).

     for R = 1:N
         for C = 1:N
             A(R,C) = 1/(R+C-1);
         end
     end

Step S with increments of -0.1
     for S = 1.0: -0.1: 0.0, do_some_task(S), end

Set E to the unit N-vectors
     for E = eye(N), do_some_task(E), end

Long loops are more memory efficient when the colon expression appears
in the for statement since the index vector is never created.

The BREAK statement can be used to terminate the loop prematurely.

用法(翻譯)

for:重複一個語句特定的次數。 for語句的一般格式是: for variable = expr, statement, …, statement END 這個expression每次都會在variable中存一次,接著執行下面的語句,直到for當次迴圈結束,繼續執行下一次。expression一般的表達形式是X:Y,表示從x>>y,迴圈Y-X次,在這種情況下它的列只是簡單的標量。

  • 下面是一些例子(假設N已經定義成某一個值)
  1. for R = 1:N for C = 1:N A(R,C) = 1/(R+C-1); end end
  2. 增量為-0.1來迴圈 for S = 1.0: -0.1: 0.0, do_some_task(S), end
  3. 假設E為N維向量 for E = eye(N), do_some_task(E), end
  • 實際在for語句中,expression向量從來都不存在,在迴圈次數很多的時候,使用:表達更加方便有效。
  • 可以使用break語句來提前跳出for迴圈。