Clear Filters
Clear Filters

Simulink/ MATLAB Function Integration

7 views (last 30 days)
Matin
Matin on 21 Jun 2023
Answered: Yash on 21 Jun 2023
Hello,
I have a main function in matlab which in a part of it, uses a simulink block (C-Caller) which contains a c code. for doing this, in the main function I have used this command:
out=sim('calc')
which "calc" is the name of my C-code containing block. Now I want to put the main function in a simulink Matlab Function block. I wanted to know how can i implement this? How should I do this when I put this function in a simulink block. In other words, how does this command change?
Best Regards

Accepted Answer

Yash
Yash on 21 Jun 2023
The sim function cannot be directly used inside a Simulink Matlab Function block because it is a top-level command for running Simulink simulations.
Instead, you can use the Simulink API functions within the Matlab Function block which will provide the same functionality as you're expecting.
You just need to replace the sim('calc') command with the necessary Simulink API functions to simulate your C-Caller block.
To do this, you need to add a MATLAB function block to your Simulink model. For that, open the Matlab Function block and write your main function code inside it. Make sure to specify the appropriate inputs and outputs for the block.
Use the following code for the same.
function out = myFunction(in)
% Define the simulation parameters
tStart = 0;
tEnd = 10;
% Load the Simulink model
load_system('calc');
% Set the input values
set_param('calc/InputBlock', 'Value', num2str(in)); % Replace 'calc/InputBlock' with the path to your input block
% Simulate the model
simOut = sim('calc', 'StartTime', num2str(tStart), 'StopTime', num2str(tEnd));
% Extract the output value
out = simOut.OutputBlock(end); % Replace 'OutputBlock' with the path to your output block
end
Here in is the input value passed to the Matlab Function block. and out is the output value returned by the Matlab Function block.
After implementing the code inside the Matlab Function block, you can connect the block to the rest of your Simulink model as needed.

More Answers (0)

Categories

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

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!