Main Content

While 循环

此示例说明如何使用 Simulink® 模块、Stateflow® 图和 MATLAB® Function 模块实现 while 循环构造。

C 构造

while(flag && (num_iter <= 100)
{
  flag = func ();
  num_iter ++;
}

While 循环的建模模式:While Iterator Subsystem 模块

创建 while 循环的一种方法是使用 Simulink > 端口和子系统库中的 While Iterator Subsystem 模块。

1.打开示例模型 ex_while_loop_SL

该模型包含一个 While Iterator Subsystem 模块,该模块在仿真时间步期间重复执行子系统的内容。

观察模型中的以下设置:

  • Constant 模块为 While Iterator Subsystem 提供初始条件。对于 Constant 模块,常量值1输出数据类型boolean。初始条件可能取决于模块的输入。

  • 在 While Iterator Subsystem 中,func 子系统模块的输出 flag01,具体取决于 func( ) 中的算法结果。func()func 子系统中的函数名称

  • 在 While Iterator Subsystem 中,对于 While Iterator 模块,最大迭代次数100

  • 对于 While Iterator 模块,While 循环类型while

2.要编译模型并生成代码,请按 Ctrl+B

实现 while 循环的代码位于 ex_while_loop_SL.c 中的 ex_while_loop_SL_step 函数中:

/* Model step function */
void ex_while_loop_SL_step(void)
{
  int32_T s1_iter;
  boolean_T loopCond;

  /* Outputs for Iterator SubSystem: '<Root>/While Iterator Subsystem' incorporates:
   *  WhileIterator: '<S1>/While Iterator'
   */
  s1_iter = 1;

  /* SystemReset for Atomic SubSystem: '<S1>/func' */
  func_Reset();

  /* End of SystemReset for SubSystem: '<S1>/func' */
  loopCond = true;
  while (loopCond && (s1_iter <= 100)) {
    /* Outputs for Atomic SubSystem: '<S1>/func' */
    func();

    /* End of Outputs for SubSystem: '<S1>/func' */
    loopCond = flag;
    s1_iter++;
  }

  /* End of Outputs for SubSystem: '<Root>/While Iterator Subsystem' */
}

While 循环的建模模式:Stateflow 图

1.打开示例模型 ex_while_loop_SF

在该模型中,ex_while_loop_SF/Chart 执行 while 循环。

该图包含 While 循环决策模式,您可以通过在图内右键点击并依次点击在图中添加构型 > 循环 > While 来添加该模式。

2.要编译模型并生成代码,请按 Ctrl+B

实现 while 循环的代码位于 ex_while_loop_SF.c 中的 ex_while_loop_SF_step 函数中:

/* Model step function */
void ex_while_loop_SF_step(void)
{
  /* Chart: '<Root>/Chart' */
  num_iter = 1;
  while (flag && (num_iter <= 100)) {
    /* Outputs for Function Call SubSystem: '<Root>/func' */
    func();

    /* End of Outputs for SubSystem: '<Root>/func' */
    num_iter++;
  }

  /* End of Chart: '<Root>/Chart' */
}

While 循环的建模模式:MATLAB Function 模块

1.打开示例模型 ex_while_loop_ML

MATLAB Function 模块包含以下函数:

function fcn(func_flag)

flag = true; 
num_iter = 1;

while(flag && (num_iter<=100))
    func;
    flag = func_flag;
    num_iter = num_iter + 1;
end

2.要编译模型并生成代码,请按 Ctrl+B

实现 while 循环的代码位于 ex_while_loop_ML.c 中的 ex_while_loop_ML_step 函数中:

/* Model step function */
void ex_while_loop_ML_step(void)
{
  int32_T num_iter;
  boolean_T flag;
  boolean_T func_flag_0;

  /* MATLAB Function: '<Root>/MATLAB Function' */
  func_flag_0 = func_flag;
  flag = true;
  num_iter = 1;
  while (flag && (num_iter <= 100)) {
    /* Outputs for Function Call SubSystem: '<Root>/func' */
    func();

    /* End of Outputs for SubSystem: '<Root>/func' */
    flag = func_flag_0;
    num_iter++;
  }

  /* End of MATLAB Function: '<Root>/MATLAB Function' */
}

另请参阅

相关示例

详细信息