How to connect input to input programmatically (add_line)?

4 views (last 30 days)
I use 'add_line()' to connect output to input, output from first block to the input of next block, in this case To File block (dropping outputs to file).
However, I would like to drop input of the first block to file too: is there an option to connect input to input, input of the first block to input of To File block?

Answers (1)

Anudeep Kumar
Anudeep Kumar on 23 Apr 2025
Hey Danijel,
I believe you want to connect your input signal to input of ‘To File’ block in order to export your input along with your output into a ‘.mat’ file.
Although ‘To File’ block has just one input port you can pass multiple inputs to it using a ‘Mux’ block.
I have provided a code snippet to add blocks and connect them accordingly in a model. You can simulate the model and observe the ‘.mat’ file which contains both input and output signals.
% Create new model
modelName = 'counter_gain_mux_to_file';
new_system(modelName);
open_system(modelName);
% Block positions
posCounter = [100 100 150 130];
posGain = [250 100 300 130];
posConv = [350 100 380 130];
posMux = [450 80 480 150];
posToFile = [600 100 650 130];
% Add blocks
add_block('simulink/Sources/Counter Free-Running', [modelName '/Counter'], 'Position', posCounter);
add_block('simulink/Math Operations/Gain', [modelName '/Gain'], 'Position', posGain, 'Gain', '2');
add_block('simulink/Commonly Used Blocks/Data Type Conversion', [modelName '/DataTypeConv'], ...
'Position', posConv, 'OutDataTypeStr', 'uint16');
add_block('simulink/Signal Routing/Mux', [modelName '/Mux'], 'Position', posMux, 'Inputs', '2');
add_block('simulink/Sinks/To File', [modelName '/ToFile'], 'Position', posToFile, 'Filename', 'output.mat');
% Connect Counter to Gain
add_line(modelName, 'Counter/1', 'Gain/1');
% Connect Counter to Mux (first input)
add_line(modelName, 'Counter/1', 'Mux/1');
% Connect Gain to Data Type Conversion
add_line(modelName, 'Gain/1', 'DataTypeConv/1');
% Connect Data Type Conversion to Mux (second input)
add_line(modelName, 'DataTypeConv/1', 'Mux/2');
% Connect Mux to To File
add_line(modelName, 'Mux/1', 'ToFile/1');
% Save and open model
save_system(modelName);
open_system(modelName);
Here is the documentation for Mux block for your reference:
Hope this helps!

Categories

Find more on Programmatic Model Editing in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!