Using Simulink from .m file
1 view (last 30 days)
Show older comments
Ali Almakhmari on 16 Jan 2023
Commented: Paul on 17 Jan 2023
I have my whole code written in a gigantic .m file. In a certain process I am doing in my code, I want to call this block (shown in picture) and give it "F" and "Ma" and take its outputs back from simulink to my code's workspace. I am struggling to do this correctly and the sim command page is poorly written to help me with this. Any help is appreciated.
Ok. If F and Ma are constants, you should consider using a Constant block for each. Make the "Constant value" paramter F and Ma, just like you already have, in each block respectively. That would probably make things a bit easier.
Assuming we are going to stick with the From Workspace block and you want F and Ma to both be constant over the simulation, the variables F and Ma actually need to be defined as F = [0 Fx Fy Fz] and Ma = [0 Max May Maz], which means set the ouput of the blocks to [Fx Fy Fz] and [Max May Maz] at time = 0. The outputs will be held constant for time > 0.
So the workflow would look like this, see this doc page for more details. Modify as needed.
% initialize Fx Fy Fz and Max May Maz to whatever values for the first
Max = 1; May = 1; Maz = 1;
Fx = 1; Fy = 1; Fz = 1;
% Initialize the Simulink.SimulationInput for the model
simIn = Simulink.SimulationInput('mysim'); % use whatever your model name is
for nrun = 1 : 5 % five runs, or whatever
% set F and Ma in simIn
simIn = setVariable(simIn, "F",[0 Fx Fy Fz],"Workspace",'mysim');
simIn = setVariable(simIn, "Ma",[0 Max May Maz],"Workspace",'mysim');
% run the simulation
simOut = sim(simIn, 'ShowSimulationManager', 'on'); % or turn ShowSimulationManger off if desired
% compute the updated values of Fax, etc. based on simOut for use next
% time through the loop
Fx = % etc
You can add the line:
simIn = setModelParameter(simIn,'StopTime',1);
to only run the simulation for 1 second. If you're using a Fixed Step solver, just set the stop time to the solver time step.
Would you mind describing what you're doing? Maybe you should be computing the updates to F and Ma in the simulation itself.
More Answers (0)
Find more on General Applications in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!