Используйте условное входное выполнение ветви

В этом примере показано, как оптимизировать сгенерированный код для модели, которая содержит Переключатель и Многопортовые блоки switch. Когда вы выбираете выполнение ветви входа Conditional параметра конфигурации модели, Simulink выполняет только блоки, которые вычисляют вход управления и ввод данных, который выбирает вход управления. Эта оптимизация улучшает скорость выполнения.

Модель в качестве примера

В этом примере условно выполняются пути к переключателю. Если Switch1 вход управления верен, Switch1 выполняет блоки, сгруппированные в Switch1:Path1 ветвь. Если Switch1 вход управления является ложным, Switch1 выполняет блоки, сгруппированные в Switch1:Path2 ветвь. Если Switch1 выполняет блоки в Switch1:Path2 ветвь и Switch2 вход управления верен, Switch2 выполняет блоки в Switch2:Path1 ветвь. Если Switch2 вход управления является ложным, Switch2 выполняет блоки в Switch2:Path2 ветвь. Псевдо код показывает эту логику.

model='rtwdemo_condinput';
open_system(model);

Сгенерируйте код

Параметр выполнения ветви входа Conditional включен по умолчанию. Введите следующий API командной строки, чтобы выключить параметр.

set_param(model, 'ConditionallyExecuteInputs', 'off');

Создайте временную папку для сборки и инспекционного процесса.

currentDir=pwd;
[~,cgDir]=rtwdemodir();

Создайте модель.

rtwbuild(model)
### Starting build procedure for: rtwdemo_condinput
### Successful completion of build procedure for: rtwdemo_condinput

Просмотрите сгенерированный код без оптимизации. Эти строки кода находятся в rtwdemo_condinput.c файл.

cfile = fullfile(cgDir,'rtwdemo_condinput_grt_rtw','rtwdemo_condinput.c');
rtwdemodbtype(cfile,'/* Model step', '/* Model initialize', 1, 0);
/* Model step function */
void rtwdemo_condinput_step(void)
{
  /* Switch: '<Root>/ Switch2' incorporates:
   *  Constant: '<Root>/ C_10'
   *  Constant: '<Root>/C_5'
   *  Gain: '<Root>/  G3'
   *  Inport: '<Root>/input'
   *  RelationalOperator: '<Root>/Relational Operator'
   *  Sum: '<Root>/ Sum'
   */
  if (rtwdemo_condinput_U.input >= -5.0) {
    rtwdemo_condinput_Y.output = 3.0 * rtwdemo_condinput_U.input;
  } else {
    rtwdemo_condinput_Y.output = rtwdemo_condinput_U.input + -10.0;
  }

  /* End of Switch: '<Root>/ Switch2' */

  /* Switch: '<Root>/Switch1' incorporates:
   *  Constant: '<Root>/C5'
   *  Inport: '<Root>/input'
   *  RelationalOperator: '<Root>/Relational Operator1'
   */
  if (rtwdemo_condinput_U.input >= 5.0) {
    /* Outport: '<Root>/output' incorporates:
     *  Constant: '<Root>/  C10'
     *  Sum: '<Root>/ Sum1'
     */
    rtwdemo_condinput_Y.output = rtwdemo_condinput_U.input + 10.0;
  }

  /* End of Switch: '<Root>/Switch1' */
}

Сгенерированный код содержит if-else оператор для Switch1 блокируйтесь и if оператор для Switch2 блок. Поэтому сгенерированный код для Switch1:Path2 выполняется даже если if оператор для Switch1:Path1 оценивает к истине.

Включите оптимизацию

  1. Откройте диалоговое окно Configuration Parameters.

  2. Выберите параметр выполнения ветви входа Conditional. В качестве альтернативы можно использовать API командной строки, чтобы включить оптимизацию.

set_param(model, 'ConditionallyExecuteInputs','on');

Сгенерируйте код с оптимизацией

rtwbuild(model)
cfile = fullfile(cgDir,'rtwdemo_condinput_grt_rtw','rtwdemo_condinput.c');
rtwdemodbtype(cfile,'/* Model step', '/* Model initialize', 1, 0);
### Starting build procedure for: rtwdemo_condinput
### Successful completion of build procedure for: rtwdemo_condinput

/* Model step function */
void rtwdemo_condinput_step(void)
{
  /* Switch: '<Root>/Switch1' incorporates:
   *  Constant: '<Root>/C5'
   *  Constant: '<Root>/C_5'
   *  Inport: '<Root>/input'
   *  RelationalOperator: '<Root>/Relational Operator'
   *  RelationalOperator: '<Root>/Relational Operator1'
   *  Switch: '<Root>/ Switch2'
   */
  if (rtwdemo_condinput_U.input >= 5.0) {
    /* Outport: '<Root>/output' incorporates:
     *  Constant: '<Root>/  C10'
     *  Sum: '<Root>/ Sum1'
     */
    rtwdemo_condinput_Y.output = rtwdemo_condinput_U.input + 10.0;
  } else if (rtwdemo_condinput_U.input >= -5.0) {
    /* Switch: '<Root>/ Switch2' incorporates:
     *  Gain: '<Root>/  G3'
     *  Outport: '<Root>/output'
     */
    rtwdemo_condinput_Y.output = 3.0 * rtwdemo_condinput_U.input;
  } else {
    /* Outport: '<Root>/output' incorporates:
     *  Constant: '<Root>/ C_10'
     *  Sum: '<Root>/ Sum'
     *  Switch: '<Root>/ Switch2'
     */
    rtwdemo_condinput_Y.output = rtwdemo_condinput_U.input + -10.0;
  }

  /* End of Switch: '<Root>/Switch1' */
}

Сгенерированный код содержит один if оператор. Сгенерированный код для Switch1:Path2 только выполняется если if оператор оценивает ко лжи.

Закройте отчет модели и генерации кода

bdclose(model)
rtwdemoclean;
cd(currentDir)

Смотрите также

| |

Похожие темы

Для просмотра документации необходимо авторизоваться на сайте