В этом примере показано, как оптимизировать сгенерированный код для модели, которая содержит Переключатель и Многопортовые блоки 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 Build Summary Top model targets built: Model Action Rebuild Reason ================================================================================================== rtwdemo_condinput Code generated and compiled Code generation information file does not exist. 1 of 1 models built (0 models already up to date) Build duration: 0h 0m 7.7574s
Просмотрите сгенерированный код без оптимизации. Эти строки кода находятся в 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_5'
* Inport: '<Root>/input'
* RelationalOperator: '<Root>/Relational Operator'
*/
if (rtwdemo_condinput_U.input >= -5.0) {
/* Switch: '<Root>/Switch1' incorporates:
* Gain: '<Root>/ G3'
*/
rtwdemo_condinput_Y.output = 3.0 * rtwdemo_condinput_U.input;
} else {
/* Switch: '<Root>/Switch1' incorporates:
* Constant: '<Root>/ C_10'
* Sum: '<Root>/ Sum'
*/
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) {
/* Switch: '<Root>/Switch1' incorporates:
* Constant: '<Root>/ C10'
* Outport: '<Root>/output'
* 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 оценивает к истине.
Откройте диалоговое окно Configuration Parameters.
Выберите параметр выполнения ветви входа 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
Build Summary
Top model targets built:
Model Action Rebuild Reason
=================================================================================
rtwdemo_condinput Code generated and compiled Generated code was out of date.
1 of 1 models built (0 models already up to date)
Build duration: 0h 0m 6.2632s
/* 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)
Условное входное выполнение ветви | Multiport Switch | Switch