Chuyển đến nội dung

Bài 5 · Getting Started

Simulink from MATLAB Scripts: sim, set_param and Building Models

Control Simulink from MATLAB code: run simulations with sim, change parameters with set_param, read values with get_param and build a model programmatically with add_block and add_line.

Clicking is fine for a first model, but real projects need repeatability. MATLAB scripts can open models, change parameters, run simulations and even build whole models from code. That lets you sweep a parameter over a hundred values, run overnight batches or generate hundreds of similar models from a table.

Simulink does not run on this site, so all MATLAB code below is read-only and written for the real product. The runnable stand-in builds a small model as a Python data structure and executes it, which shows what add_block, add_line and sim do conceptually.

The core commands

Command Purpose
open_system('name') Open a model window
load_system('name') Load a model without showing it
new_system('name') Create an empty model
save_system('name') Save the model file
close_system('name', 0) Close; the 0 discards changes
sim('name') Run a simulation
set_param(object, 'Param', value) Set a model or block parameter
get_param(object, 'Param') Read a parameter
add_block(src, dest) Add a block from a library or copy one
add_line(sys, 'A/1', 'B/1') Connect output port 1 of A to input port 1 of B
find_system(...) Search a model for blocks

Parameter values are almost always character vectors or strings, even for numbers: set_param('m/Gain', 'Gain', '2.5').

Running and tuning a model

MATLAB
load_system('first_model');
set_param('first_model', 'StopTime', '20');           % simulated seconds
set_param('first_model/Sine Wave', 'Frequency', '3'); % block parameter
out = sim('first_model');                            % returns SimulationOutput
disp(out.tout(end))                                  % 20

To override parameters for one run without editing the model, use a SimulationInput object (R2017a and later), which also works with parsim for parallel runs:

MATLAB
in = Simulink.SimulationInput('first_model');
in = in.setModelParameter('StopTime', '5');
in = in.setBlockParameter('first_model/Sine Wave', 'Amplitude', '2');
out = sim(in);

Reading block parameters:

MATLAB
amp = get_param('first_model/Sine Wave', 'Amplitude');   % a char vector like '1'
dlg = get_param('first_model/Sine Wave', 'DialogParameters'); % struct of names

A parameter sweep

MATLAB
gains = [0.5 1 2 4];
peaks = zeros(size(gains));
for k = 1:numel(gains)
    in = Simulink.SimulationInput('plant_model');
    in = in.setBlockParameter('plant_model/Gain', 'Gain', num2str(gains(k)));
    out = sim(in);
    peaks(k) = max(out.logsout.get('y').Values.Data);
end
disp(table(gains', peaks', 'VariableNames', {'Gain','Peak'}))

For long sweeps replace sim with parsim(in_array) (Parallel Computing Toolbox) to use several cores.

Building a model with code

The block path 'simulink/Sources/Sine Wave' names a library block. The first argument of add_block is the source; the second is the destination path model/BlockName.

MATLAB
name = 'built_by_script';
new_system(name);
open_system(name);

add_block('simulink/Sources/Sine Wave', [name '/Sine'], 'Position', [30 40 80 80]);
add_block('simulink/Math Operations/Gain', [name '/Gain'], 'Gain', '2', ...
          'Position', [130 40 180 80]);
add_block('simulink/Sinks/Scope', [name '/Scope'], 'Position', [230 40 280 80]);

add_line(name, 'Sine/1', 'Gain/1');
add_line(name, 'Gain/1', 'Scope/1');

set_param(name, 'StopTime', '10');
save_system(name);
sim(name);

Position is [left top right bottom] in pixels. The names after the slash are block names; if a name contains a space or newline, use 'Sine Wave/1'. Use Simulink.BlockDiagram.arrangeSystem(name) to tidy the layout automatically.

Script-driven modeling

load_system Open without a window
set_param Change settings
sim Run the model
out.logsout Read the results

Parameters are strings.

1 / 2

A stand-in for add_block, add_line and sim

The Python below builds a model as a dictionary, wires it, sorts it and runs it, in the same order you would use in MATLAB.

Python Stand-in: build a model from code and run it (Python)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This stand-in is only about 30 lines, but it contains the same three ideas as the real commands: blocks are objects with parameters, lines are pairs of ports, and a simulation orders the blocks and steps through time.

Good practice

  • Wrap setup and runs in functions or scripts under version control, not in your head.
  • Use Simulink.SimulationInput instead of editing the model for each run; it leaves the model file unchanged.
  • Use bdclose all at the end of batch scripts; models stay loaded in memory otherwise.
  • Check get_param(gcs, 'SimulationStatus') ('stopped', 'running', 'paused') when you control runs interactively.
  • Keep gcb (current block path) and gcs (current system) in mind for quick experiments.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What type should the value argument of set_param normally be?

    Block and model parameters are set with text such as '2.5', even for numbers.
  2. 2. What does add_line('m', 'A/1', 'B/2') do?

    add_line connects a source output port to a destination input port.
  3. 3. Which tool lets you run a simulation with changed parameters without editing the model file?

    SimulationInput carries per-run overrides and works with sim and parsim.
  4. 4. What does close_system('m', 0) do?

    The 0 argument means do not save changes.

Summary

  • sim, set_param, get_param, load_system and save_system let you run and tune models from scripts.
  • Parameter values are text; use num2str to convert numbers.
  • Simulink.SimulationInput and parsim run many variations without touching the file.
  • new_system, add_block and add_line can build a model entirely from code.

Next: Sources, Sinks and Math Blocks

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.