Guy on Simulink https://blogs.mathworks.com/simulink Guy Rouleau is an Application Engineer for MathWorks. He writes here about Simulink and other MathWorks tools used in Model-Based Design. Mon, 04 Nov 2024 16:48:27 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.2 The Most Impactful Recent Features in Simulink https://blogs.mathworks.com/simulink/2024/11/04/the-most-impactful-recent-features-in-simulink/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2024/11/04/the-most-impactful-recent-features-in-simulink/#comments Mon, 04 Nov 2024 16:48:27 +0000 https://blogs.mathworks.com/simulink/?p=17246

I have been recently asked this question:What are the top 10 most impactful and recent features for Simulink and Model-Based Design?It's a tricky question because different workflows are impacted by... read more >>

]]>
I have been recently asked this question:
What are the top 10 most impactful and recent features for Simulink and Model-Based Design?
It's a tricky question because different workflows are impacted by different features. Something life-changing for one user can go unnoticed by someone else. Also, the meaning of "recent" depends a lot on how often you update to new versions.
I have been supporting Simulink users and writing this blog for more than 15 years. When coming up with the following list, I tried to reflect on how the workflows I see the most when talking to users have changed throughout the years and which features have impacted them the most.
I decided to divide this in four categories:
  • Model Execution and Performance
  • Model Management
  • Model Authoring
  • Toolboxes and Blocksets

Model Execution and Performance

Let's state the obvious: We all like it when simulations run fast!
To help with that, we published in the last few years a technical article (Improving Simulation Performance in Simulink) and a YouTube livestream (Speed up Simulink Simulation Workflows). Here are three features highlighted in this article and video.

Model Reference - Accelerated and Protected

The Model Reference technology has been in Simulink for many years. It enables using a Simulink model as part of another model. The reason why I am mentioning it here is that it can help a lot with performance, especially the time it takes to initialize a simulation.
In MathWorks Technical Support, we often receive questions along the line of "How can I make my Simulink model faster?".
At each release cycle, we review and analyze the requests we received and how we addressed them. In the last few years, the feature that helped users speed up their simulation the most is accelerated and protected referenced models. When used properly (see this post on chache and rebuild), model referencing can significantly speed up the time required to initialize a simulation.
Here is a slide from our YouTube livestream that I like to use to describe my recommended workflow with referenced models:
The assumption here is that when dealing with large simulations, on a given day, most users only need to modify a small part of it. If that's your case, do two things:
  • Place the parts you are not modifying in referenced models configured to run in accelerator mode. It will take some time to pre-compile them the first time, but for subsequent simulation they will initialize instantly.
  • For the parts you are actively working on, place them either in the top model, inside a referenced subsystem, or inside a referenced model configured to run in normal mode.

Fast Restart

Fast Restart complements model reference very well. It is useful for cases where you need to run many simulations without making structural changes to a model. We call it the "Tune-Sim-Repeat" workflow:
With Fast Restart enabled, the model will be compiled once. At the end of the simulation, the status bar will look like this:
When in that mode, the initialization time of the next simulation will go down to practically zero.
Many Simulink features have options to leverage Fast Restart. The first ones that come to my mind are:

Parsim and Batchsim

Parsim and batchsim make it easy to run multiple simulations in parallel. Before the introduction of those functions, simulating models in parallel was quite complex. At that time, I wrote this blog post to explain all the subtleties to get the data needed by the simulation available to the parallel workers.
In newer versions of MATLAB, you can almost always simply replace the sim command with parsim or batchsim and it just works.
Parsim and batchsim do not make one simulation faster, what they enable is running multiple simulations at the same time, either on your local computer, on a MATLAB Parallel Server, or in the cloud.
When using parsim, you can use the Simulation Manager to monitor the progress of your simulations

Model Management and Componentization

When not done properly, model management and componentization can cause a lot of headaches. Here are 3 features that can help with that.

Projects

Initially introduced as "Simulink Projects", we now talk about MATLAB Projects because they apply not only to Simulink, but to the entire MathWorks ecosystem.
Project are super useful to organize all the files around a Simulink model and automate common tasks. Even when I receive files from users that are not inside a project, I often create a project to make my life easier.
When I start writing a new blog post like this one, I always start from a Project Template that I created at the time when I decided to make it possible to view and run posts in MATLAB Online. (You can download my Project Template).
My favorite features with Projects are:
Projects can also reference other projects to componentize large projects.

Variants

With variants, a single Simulink model can contain multiple designs, and you can decide which one is active when the model is simulated or when you generate code from it. You can control the active variant using expressions and/or variant configurations.
The classic example is a simulation that can be configured to represent a vehicle with a gasoline engine, an electric motor, or a hybrid drivetrain.
If you want to learn more about all the possibilities enabled by variants, I recommend:
If you are already using variants, I recommend looking at the Variant Manager. This tool can help manage, reduce and analyze variants present in your Simulink models.

Subsystem Reference

Subsystem Reference enables something simple and obvious but very useful: Save the content of a Subsystem in a separate file.
In my opinion, this provides a perfect complementary solution to referenced models, which have a stricter interface (which enables more possibilities as described above), and libraries, which are better suited for a collection of blocks changing infrequently to be shared with many users.
If you are not sure when to use model reference, versus subsystem reference, versus libraries, see: Component-Based Modeling Guidelines

Model Authoring

In my work, I edit Simulink models all day, every day. Because of that, features that allow me to edit models faster and more efficiently have a huge impact.
Tons of enhancements have been added to the Simulink editor throughout the years. Out of the lot, two stand out to me.

Quick Insert

Before Quick Insert, we had to navigate the Library Browser, find the blocks you wanted and drag them into the canvas. Since the introduction of Quick Insert, you can simply type what you need in the canvas and hit Enter. On top of that, if you double-click on the tip of an unconnected line, the Quick Insert menu will offer the blocks you are the most likely to want to add based on the context. You can even train this algorithm with your own models:
QuickInsert.gif
Once you are in the Quick Insert menu, you can toggle to Action Search using the keyboard shortcut "Ctrl+." and search for Simulink actions and apps:

Commenting Blocks

I must admit, the first time I heard plans to add the possibility to comment blocks, my reaction was: Why would someone need that? If I want to temporarily remove blocks from a model, I can cut and paste them in an empty temporary model.
I was so young and innocent...
Today, I comment out and comment through blocks all day every day and I rarely receive models from users that don't have at least a few blocks commented out.

Pro Tip:

The keyboard shortcuts for commenting blocks are:
  • Comment out: Ctrl+Shift+X
  • Comment through: Ctrl+Shift+Y
Other apps on your computer might also use Ctrl+Shift+X and could highjack it from Simulink (SnagIt, the software I use to take screenshot for this blog, does that). I personally disable those in other software so Ctrl+Shitf+X can remain associated with Simulink.
Comment.gif

Toolboxes and Blocksets

Let's talk about toolboxes and blocksets that build on top of the Simulink foundation.

The Simscape Family

What started initially with simple mechanical and hydraulic domains can now be used to model pretty much anything you can think of. Here is a screenshot from the documentation listing all the domains available:
And if there is not a domain for what you need, you can create your own using the Simscape Language.
If you have not used Simscape yet, here is a screenshot of a model simulating a Medical Ventilator with Lung Model. It combines mechanical, thermal, and moist air domains.
I personally receive tons of models from users that are composed of a plant and a controller. Throughout the years, the percentage of models using Simscape for plant modeling has continuously increased. In the last few years, I think I have seen more models where the plant is modeled using Simscape than Simulink continuous blocks.

Simulink Compiler

Simulink Compiler enables you to share Simulink simulations with anyone who does not have MATLAB.
I like to oversimplify the concept of Simulink Compiler by saying that all it does is add support to the sim command to MATLAB Compiler. It's a bit more than that, but with Simulink Compiler you can turn any Simulink simulation into:

Now it's your turn

Tell us in the comments below which recent Simulink features impacted your workflows the most.

]]>
https://blogs.mathworks.com/simulink/2024/11/04/the-most-impactful-recent-features-in-simulink/feed/ 1
Capabilities for Modeling Dynamic Systems and Designing Feedback Control Systems in MATLAB and Simulink https://blogs.mathworks.com/simulink/2024/10/28/capabilities-for-modeling-dynamic-systems-and-designing-feedback-control-systems-in-matlab-and-simulink/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2024/10/28/capabilities-for-modeling-dynamic-systems-and-designing-feedback-control-systems-in-matlab-and-simulink/#respond Mon, 28 Oct 2024 19:12:48 +0000 https://blogs.mathworks.com/simulink/?p=17195

In today's post, I want to share a few links. I shared those with individual users recently, and every time the response I get is "Wow, those are super useful, I wish I knew about them earlier"The... read more >>

]]>
In today's post, I want to share a few links. I shared those with individual users recently, and every time the response I get is "Wow, those are super useful, I wish I knew about them earlier"
The following resources will give you an overview of everything available to model and control systems in MATLAB and Simulink, so you can pick the right tool for your needs.

Capabilities for Modeling Dynamic Systems

This first page is about modeling dynamic systems. It contains a high-resolution poster covering all the possible ways to model dynamic systems in MATLAB and Simulink.
For each section of the poster, the page includes links to discovery pages and relevant documentation.
We have used many of those techniques on this blog in the past, here are a few examples where we modeled and simulated dynamic systems:
If you're more into videos, the author of the poster, Brian Douglas, also made a video version available on youtube.

Capabilities for Designing Feedback Control Systems

This second page uses a similar framework, but covering the capabilities for designing feedback control systems.
It also comes with a series of almost 100 videos covering everything you need to know about control systems

Now it's your turn

What is your favorite resource for discovering the capabilities for modeling and controller design in MATLAB and Simulink? Let us know in the comments below.

]]>
https://blogs.mathworks.com/simulink/2024/10/28/capabilities-for-modeling-dynamic-systems-and-designing-feedback-control-systems-in-matlab-and-simulink/feed/ 0
How to correct errors in port width or dimension in Simulink? https://blogs.mathworks.com/simulink/2024/09/19/how-to-correct-errors-in-port-width-or-dimension-in-simulink/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2024/09/19/how-to-correct-errors-in-port-width-or-dimension-in-simulink/#comments Thu, 19 Sep 2024 19:56:16 +0000 https://blogs.mathworks.com/simulink/?p=17147

Let's continue our tour of the most viewed Simulink-related MATLAB Answers. This week, we look at:How to correct error in port width or dimension in simulink ?While this error mentions dimensions,... read more >>

]]>
Let's continue our tour of the most viewed Simulink-related MATLAB Answers. This week, we look at:
While this error mentions dimensions, the same principles and techniques to debug this error apply also to other properties like data types and sample times.

The Problem

To begin, let's recreate a model similar to the one in the MATLAB Answers post:
mdl = "PropagationIssue";
out = sim(mdl,"CaptureErrors","on");
out.ErrorMessage
ans =
'Error due to multiple causes. Caused by: Invalid setting for input port dimensions of 'PropagationIssue/Demux'. The dimensions are being set to [-1]. This is not valid because the total number of input and output elements are not the same Error in port widths or dimensions. Invalid dimension has been specified for 'Output Port 1' of 'PropagationIssue/Transfer Fcn'.'

A First Solution

In this specific model, my best guess is that the user thought that they had to use a Demux block to send a signal to two destinations. The simplest way to fix this model is to get rid of the Demux block and simply branch the signal. To branch a signal, you can right-click on it and drag.
RemoveDemux.gif
While this model is easy to fix, getting this error in a more complex model can be challenging. Let's see how I typically debug this error.

Debugging Tips

When running into propagation errors, there are typically two blocks reported: The source and the destination. In this case we have:
The error happens because there is a disagreement between those two blocks.
When initializing a model, Simulink interrogates each block to determine if their ports must have a specific dimension, or if they can inherit it. If they can inherit a dimension, Simulink will propose a value based on the upstream or downstream blocks and the block will respond to let Simulink know if it can accept the proposed dimension.
Here is how I picture this negotiation:

Display Signal Dimensions

When debugging dimension issues, I recommend enabling "Signal Dimensions" and "Nonscalar Signals" from the "Information Overlays"
Then I like to try the following two options.

Option 1: Ground and Terminators

By disconnecting the two problematic blocks, you might be able to get a successful update diagram (Ctrl+D) and see which dimensions Simulink is trying to propagate on each side. In this case, we can see that the Transfer Function wants to output a dimension of 1, while the Demux wants a dimension of 2:

Option 2: Signal Specification

When I know what the dimension should be, I like to try inserting a Signal Specification block and specifying the known dimension. In this negotiation between Simulink and all the blocks, the Signal Specification enforces the dimension of the signal, which usually helps getting a clearer error. At a minimum, it should help you determine which one of the two conflicting ports is trying to propagate the unexpected dimension.
With those two techniques, I usually get the information I need to understand what I did wrong and modify the model to resolve the error.

The Demux block

There is another part to the error, specific to the Demux block:
  • The dimensions are being set to [-1]. This is not valid because the total number of input and output elements are not the same
Let's dissect this.

[-1]

In Simulink, the value of "-1" for most properties usually means "inherited". For example, if you drag an Inport block in a model, the default value for Port dimensions is set to "-1":

Demux Specification

As mentioned in its dialog, the Demux block can be used to split vector signals into scalars or smaller vectors. The thing to realize is that it can be configured in two ways.

Option 1: Number of Ports

In that case, Simulink will try to evenly spread the incoming vector among the number of specific ports. In this example, we receive 5 and split it in 3 and 2:
When the block is configured that way, it's like saying that the dimension of the individual ports is set to "-1".

Option 2: Dimension per ports

If I want two ports, but split the vector of 5 into 4 and 1, I can specify that as a vector where the number of elements is the number of ports:
With all that being said, because of the feedback loop in the original model, what the Demux block is trying to say through this error is that the only way the model could update is if the dimension of its input signal is the same as its output.

Now it's your turn

Do you have tips and tricks for debugging dimensions propagation issues in Simulink? Let us know in the comments below.

]]>
https://blogs.mathworks.com/simulink/2024/09/19/how-to-correct-errors-in-port-width-or-dimension-in-simulink/feed/ 2
What’s New in Simulink in R2024b? https://blogs.mathworks.com/simulink/2024/09/12/whats-new-in-simulink-in-r2024b/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2024/09/12/whats-new-in-simulink-in-r2024b/#comments Thu, 12 Sep 2024 18:39:31 +0000 https://blogs.mathworks.com/simulink/?p=17021

Looking at the Release Notes for Simulink in R2024b, what stands out the most to me is that we have improved a lot of already existing features. Let's look at my favorites of those enhancements.New... read more >>

]]>
Looking at the Release Notes for Simulink in R2024b, what stands out the most to me is that we have improved a lot of already existing features.
Let's look at my favorites of those enhancements.

New Details panel for Quick Insert

When it was introduced many releases ago, the Quick Insert menu was a huge game changer. It completely changed the way to add blocks to a Simulink model. Instead of navigating the Library Browser and dragging the block into the model, Quick Insert allows you to just type the name of the block in the canvas and hit Enter.
In R2024b, we are adding a Details panel to this menu. It provides a description of the block and hyperlinks to documentation and examples:

Starting a Simulation in Debug mode

In R2023b, we introduced a new way to debug Simulink models, with the in-canvas debugger. Since then, the way to launch the block-by-block debugger was to add breakpoints on signal lines so the debugger would break as soon as the condition is met.
In R2024b, we decided to enable the Step Over button in the toolstrip when the simulation is stopped. Starting the simulation with this button will pause the simulation just before the first block executes, ready to debug from t=0. This is especially useful when the problem you are investigating is not obvious to capture with a change in value of a signal. Here is an example:
StepOver2.gif

Connecting blocks across model hierarchy

The ability to programmatically create Simulink models is a major power of MATLAB + Simulink. For those using the add_block and add_line functions, you will love the new Simulink.connectBlocks.
Let's take this model:
I can connect the Gain block inside Subsystem A to the Bias block inside Subsystem B using this code:
blk1 = 'testConnect/A/Gain';
blk2 = 'testConnect/B/Bias';
Simulink.connectBlocks(blk1,blk2);
This will automatically add the Inport and Outport blocks required and connect all those blocks together.
In this case the result is one line of code instead of two calls to add_blocks and three calls to add_line. For more complex cases across deep hierarchies, the benefit is more significant. Look at the documentation for Simulink.connectBlocks to see all the possibilities.

Improved Bus handling in Model Reference Conversion Advisor

Let's say I have a simple model with a bus signal entering a Subsystem:
I can now convert it to a Referenced Model and the resulting model will look exactly like the original, and the bus element ports will include the entire bus definition, so no need for bus objects.

Customize Sample Time Colors

Since the beginning of time, sample time colors in Simulink have always been the same: D1 is red, D2 is green, D3 is blue, etc. In R2024b, we finally implemented the long-standing request of allowing users to customize sample time colors.
It's quite simple. Create a simulink.sampletimecolors.Palette object, define your colors in RGB or Hexadecimal color code and apply it:
h = simulink.sampletimecolors.Palette("myColors");
h.DiscreteSampleTimeColors = ["#aed6f1"; "#85c1e9";"#3498db";"#2874a6"];
simulink.sampletimecolors.applyPalette(h);
Here the resulting sample time legend for my "50 shades of blue" palette:

Adding Model blocks and Referenced Subsystems made easier

This one is very straightforward: Drag a Simulink file from the Current Folder Browser into a Simulink model, and we automatically insert a Model or Subsystem block referencing it.
AddModel.gif

Now it's your turn

Look at the Release Notes and let us know what your favorite feature in Simulink R2024b is, or if there are other features you would like me to cover on the blog.

]]>
https://blogs.mathworks.com/simulink/2024/09/12/whats-new-in-simulink-in-r2024b/feed/ 2
How can I create an impulse (delta) signal in Simulink? https://blogs.mathworks.com/simulink/2024/08/23/how-can-i-create-an-impulse-delta-signal-in-simulink/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2024/08/23/how-can-i-create-an-impulse-delta-signal-in-simulink/#comments Fri, 23 Aug 2024 19:07:41 +0000 https://blogs.mathworks.com/simulink/?p=16978

Here is another frequently visited page on MATLAB Answers:How can I create an impulse (delta) signal in Simulink?The ProblemLet's first look at what Wikipedia has to say about the Dirac delta... read more >>

]]>
Here is another frequently visited page on MATLAB Answers:

The Problem

Let's first look at what Wikipedia has to say about the Dirac delta function:
"In mathematical analysis, the Dirac delta function (or δ distribution), also known as the unit impulse,[1] is a generalized function on the real numbers, whose value is zero everywhere except at zero, and whose integral over the entire real line is equal to one.[2][3][4] Since there is no function having this property, modelling the delta "function" rigorously involves the use of limits or, as is common in mathematics, measure theory and the theory of distributions."
In its ideal form, the impulse should have an infinite amplitude at t=0
and the area under the curve should be 1:
In other words, the Dirac delta function is a theoretical concept that cannot really be simulated.

Impulse Response

Before seeing how to implement a Dirac delta function in Simulink, let's talk a bit about why would someone need that.
If you are looking into implementing an impulse or Dirac delta function, it's very likely that you want to compute the impulse response of a system. Computing the impulse response is a common way to characterize the dynamic response of a system. This is used in many areas like vibrations and acoustics.
As an example, let’s define a system with two poles, one at 5 rad/sec and one at 50 rad/sec.
sys = tf(12,[1 0.5 25]) + tf(100,[1 2 2500]);
figure
bode(sys)
As a reference, let's start with the impulse function from the Control System Toolbox to see how the system responds to an impulse.
tFinal = 5;
[y,t] = impulse(sys,tFinal);
figure
plot(t,y)
Let's now look at how something similar could be implemented in Simulink.

Fixed-Step Solver

The implementation of an impulse in Simulink will probably be different if implemented fixed versus variable step. Let's begin with the fixed-step case.
With a discrete signal, the Hit Crossing block outputs a value of 1 for one time step when the specified hit crossing offset is crossed. To respect the Dirac definition that the area under the curve must be equal to 1, we can divide this signal by the sample time.
mdl = "impulse_ex_discrete";
open_system(mdl);
In this example, I want to trigger the impulse to happen when the output of the Digital Clock block crosses a specific value, let's say 1 second.
Using the same transfer function as in our previous example, we can see that the results match.
out = sim(mdl);
figure;
plot(t+1,y,'LineWidth',2) % Offset the time reference by 1 second
hold on
plot(out.yout{1}.Values)
legend('MATLAB','Simulink')

Variable-Step Solvers

With a variable-step solver, there are a few subtle things that you need to take care of.

Impulse at t=0

If what you need is an impulse at t=0, I recommend using the Step block. This will allow you to control the amplitude and duration of the pulse.
mdl = "impulse_ex_1";
open_system(mdl);
The important thing to decide is the value to use for the duration and amplitude of the impulse. Since this is impossible to generate an infinitely large amplitude with an infinitely small width, we need to pick a number.
Let's simulate the model with different values for the amplitude and width of the impulse. To respect the assumption that the integral of the pulse is 1, I make the amplitude the inverse of the duration.
p = [1e-6 0.1 1];
in = repmat(Simulink.SimulationInput(mdl),length(p),1);
for i = 1:length(in)
    in(i) = in(i).setVariable('impulseDuration',p(i));
    in(i) = in(i).setVariable('impulseAmplitude',1/p(i));
end
out = sim(in,'ShowProgress','off');
The key thing to realize is that the longer the duration of the impulse, the more it becomes a step instead of an impulse. In the Laplace world, an ideal Diract delta function has an amplitude of 1 for all frequencies, while a step has an amplitude of 1/s. The longer the impulse, the less it excites high frequencies.
Looking at the results, we can see that the second mode at 50 rad/sec is significantly less excited when the duration of the step becomes longer.
figure;hold on;
plot(t,y,'LineWidth',2)
for i = 1:length(out)
    plot(out(i).yout{1}.Values)
end
legend(['Ideal' arrayfun(@num2str, p, 'UniformOutput', false)])

Impulse at times other than zero

While the definition of the Dirac delta function says it should return a non-zero value only at t=0, it can be useful to generate an impulse at other times.
As a first attempt, it would be tempting to use a pattern similar to the one used for fixed-step. The challenge here is that with a variable-step solver, we don't have direct control on the duration of the pulse generated by the Hit Crossing block.
Based on what I know from zero-crossing detection, I guessed a gain value of 1e14 for the amplitude of the pulse, but we can see that it's not quite right.
mdl = 'impulse_ex_2';
in = Simulink.SimulationInput(mdl);
out = sim(in);
figure;hold on;
plot(t+1.23456,y,'LineWidth',2)
plot(out.yout{1}.Values)

Scheduling the Impulse Duration

To control the duration of the impulse, it is possible to use the Hit Scheduler block. When the time to trigger the impulse is detected by the Hit Crossing block we do two things: First, the event TrigOn is sent to the Stateflow chart to initiate the impulse. Then the Hit Scheduler schedules a second event TrigOff to be sent to the chart after a specified amount of time to terminate the impulse.
mdl1 = "impulse_ex_2c";
open_system(mdl1);
If you prefer, you can slightly simplify the logic by using the Discrete-Event Chart from SimEvents. In that case, you would configure the Hit Crossing block to output a message instead of a signal. This message will wake up the chart, and the chart will keep the impulse on for a duration specified using after.
mdl2 = "impulse_ex_2b";
open_system(mdl2);
out1 = sim(mdl1);
out2 = sim(mdl2);
figure;hold on;
plot(t+1.23456,y,'LineWidth',2)
plot(out1.yout{1}.Values)
plot(out1.yout{1}.Values)
legend("MATLAB", "Hit Scheduler", "Discrete-Event Chart");

Approximation using a normal distribution

If you took the time to read the Wikipedia page on the Dirac delta function, you might have noticed that another option is to implement the impulse as a normal distribution in the form:
To implement that, I can use the same logic as before to initiate and terminate the pulse. Instead of just outputting an on/off signal, I can use an Enabled Subsystem to "play" the normal distribution function.
mdl = "impulse_ex_3_b";
open_system(mdl);
out = sim(mdl);
In this case, we can see that the results match what we got from the impulse function.
figure;
subplot(2,1,1)
plot(out.logsout.get('u').Values)
axis([1.236 1.244 -10 600]);
subplot(2,1,2)
plot(out.logsout.get('y').Values)
hold on% compare to reference
plot(t+1.23456,y)

Now it's your turn

Have fun implementing impulses or Dirac delta functions in your Simulink model. If you have other techniques, share in the comments below.

]]>
https://blogs.mathworks.com/simulink/2024/08/23/how-can-i-create-an-impulse-delta-signal-in-simulink/feed/ 3
Pole Vault – 2024 Olympics update https://blogs.mathworks.com/simulink/2024/08/02/pole-vault-2024-olympics-update/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2024/08/02/pole-vault-2024-olympics-update/#comments Fri, 02 Aug 2024 15:01:05 +0000 https://blogs.mathworks.com/simulink/?p=16851

In 2016, we published this blog post simulating a pole vault jump. I decided to revisit this topic and demonstrate how I would simulate this using the latest features in Simulink.Pole Vault ModelHere... read more >>

]]>
In 2016, we published this blog post simulating a pole vault jump. I decided to revisit this topic and demonstrate how I would simulate this using the latest features in Simulink.

Pole Vault Model

Here is an illustration of what a pole vault jump looks like:
To simulate this event, we can divide the jump in three phases:
  • Approach: During this phase the athlete tries to maximize his speed along the runway to achieve maximum kinetic energy
  • Take off and swing up: The athlete positions the pole into the “box” to convert the kinetic energy into stored potential energy in the pole and swing up.
  • Fly away: The vaulter releases the pole and falls back on the mat under the influence of gravity
In 2016, the way to model that was using a series of 3 If Action Subsystems. When switching from one phase to the next, we would transfer the states from one Subsystem to the next using the Integrator block state port and GoTo and From blocks.
This semantic had multiple imitations. Let's see my preferred way to implement the same equations in MATLAB R2024a.

Simulink States inside Stateflow

Here is what my new model looks like.
mdl = "poleVaultSim";
open_system(mdl);
Yes, this is correct, only one Stateflow Chart. Don't be fooled, the Simulink blocks are inside!
The Stateflow chart is made of 4 Simulink States and 2 Simulink functions.
During the Run Up phase, I integrate the motion of the athlete running at a constant speed. Compared to the 2016 implementation, I am able to use the Second Order Integrator instead of two Integrator blocks, because the Second Order Integrator does not have a state port option.
During the Take Off, the motion of the athlete is computed in polar coordinate. This makes it simpler to solve the equations for the bending of the pole.
The important part to notice is what happens in the Simulink Functions. Using State Reader blocks, I can access the states of the Integrator blocks in the previous phase and compute the initial states of the next phase. I can then use State Writer blocks to initialize the Integrator blocks in the next phase.
When simulating the model, we can follow the evolution of the simulation through the Stateflow animation and the newly revamped XY Graph block, which is just a pre-configured instance of the Record block.
PoleVault.gif

Design Study

Let's see the impact on the jump of two variables:
  • The stiffness of the pole
  • The initial angle of the pole for the take-off phase
For that, I create two multisim variables and combine them using simulink.multisim.Exhaustive.
mdl = "poleVaultSim";
k_var = simulink.multisim.Variable("k", linspace(0.1,10,5));
theta0_var = simulink.multisim.Variable("theta0", linspace(10,50,5));
MyCombination = simulink.multisim.Exhaustive([k_var, theta0_var]);
d = simulink.multisim.DesignStudy(mdl,MyCombination);
d.PostSimFcn = @(simOut, simIn) myPostSim(simOut,simIn);
out = parsim(d,'ShowProgress','off','UseFastRestart','on');
I also create a post-sim function where I do two things:
  • I store the input variables in the SimulationOutput object
  • I process the logged data to compute the maximum height and distance of the jump
function simOut = myPostSim(simOut,simIn)
% Transfer input variables to SimulationOutput object
for i = 1:length(simIn.Variables)
    simOut.(simIn.Variables(i).Name) = simIn.Variables(i).Value;
end
% Compute key performance indicators
simOut.maxHeight = max(simOut.logsout.get('y').Values.Data);
simOut.distance = abs(simOut.logsout.get('x').Values.Data(end));
Once the simulations complete, we can visualize results in multiple ways. Let's try a few things.
Let's begin by plotting all x-y timeseries:
figure;hold on;
for i = 1:length(out)
    plot(out(i).logsout.get('x').Values.Data,out(i).logsout.get('y').Values.Data)
    legendText{i} = ['k = ' num2str(out(i).k) ', theta0 = ' num2str(out(i).theta0)];
end
legend(legendText,'Location','northeastoutside');
Maybe a matrix of scatter plots would help visualize this data?
u = [[out.k]' [out.theta0]'];
y = [[out.maxHeight]' [out.distance]'];
figure;
plotmatrix(u,y);
or a 3d bar plot?
height = reshape([out.maxHeight],5,5);
figure
bar3(height);
In the end, this seems pretty clear that the lower stiffness and initial angle result in the higher jump.

Now it's your turn

Don't miss the actual pole vault competition at the Paris Olympic:
How would you simulate the pole vault competition? Let us know in the comments below.

]]>
https://blogs.mathworks.com/simulink/2024/08/02/pole-vault-2024-olympics-update/feed/ 1
Shot Put – Olympics 2024 Update https://blogs.mathworks.com/simulink/2024/07/31/shot-put-olympics-2024-update/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2024/07/31/shot-put-olympics-2024-update/#respond Wed, 31 Jul 2024 14:18:47 +0000 https://blogs.mathworks.com/simulink/?p=16710

With the Paris Olympics going on, I decided to revisit the simulation of the shot put event that we published in 2016. BackgroundI recommend visiting the 2016 blog post for more background on how we... read more >>

]]>
With the Paris Olympics going on, I decided to revisit the simulation of the shot put event that we published in 2016.

Background

I recommend visiting the 2016 blog post for more background on how we put decided to simulate this Olympic event. In short, at the shot put event the athlete needs to throw a "shot", a round weight, a far as they can within a specific zone. This is typically done by first spinning to generate momentum and then unwind and push the weight.
To implement that in Simulink, we used a series of solids and joints from Simscape Multibody. Here is what it looks like in the Mechanics Explorer:
ShotPut.gif
Let's see how I started with the 2016 model and improved it using new features available in MATLAB R2024a.

Upgrade Advisor

The first thing I did when opening the model from R2016 is to run the Upgrade Advisor. The Upgrade Advisor is a useful tool that can identify potential enhancements to a model to take advantage of new features. In this case, it flagged 3 items:
The Upgrade Advisor was able to automatically apply the following changes:
  • Configure the model to use the solver "daessc" for Simscape models with differential algebraic equations. This new solver is more robust to solve the type of equations produced by Simscape.
  • Change the Solver Configuration block to use state-based absolute and relative consistency tolerances during initialization. Introduced in R2022b, this provides better robustness and efficiency during the initialization, especially when using Simscape nominal values.
  • Update Simscape physical signal blocks to propagate units, which was not possible in 2016. In my case, for example, it set the unit of the PS Constant block to "rad/s" because that's what the Revolute Joint downstream expects.
After just a few clicks, the model was ready to use in MATLAB R2024a.

Locking Joints

In 2016, in order to keep the shot in the hand of the athlete, we had to implement a custom force rule that would be disabled at the time of releasing the shot. This was not ideal because this force rule was computationally expensive and making the simulation slow.
So the first improvement I did to the model is leveraging the "mode" property of Simscape Multibody joints. This feature, introduced a few releases ago, allows any joint to be locked or unlocked based on an input signal.
This adds an input port to the Joint block that I can control from my Stateflow chart.

Solid Block Frames

Another feature added to Simscape Multibody that I like is the possibility to add additional frames to the Solid blocks. For each section of the arm, I defined frames at both ends of the limb.
That way, I can get rid of the Rigid Transform blocks that had to be used before. There is nothing fundamentally wrong with using Rigid Transform, but I find adding frames to the Body block makes the model easier to understand at first look.
With those changes, here is what the model looks like:

Logging Simscape Variables as Simulink Signals

The last change I made to the model is in the Sensing subsystem. In 2016, we had to use Transform Sensor blocks and PS-Simulink blocks to get the information we needed out of Simscape Multibody. In R2024a, we added the possibility to directly log Simscape variables as if they were Simulink signals.
When selecting a Simscape block, go to the Simscape Block tab in the toolstrip and enable Log Variables. In the Model Data Editor, you will see a Simscape Variables tab appear where you can select which variables to log and give them the name you desire.
When simulating the model, they will show up in the "logsout".
mdl = "ShotPut";
out = sim(mdl);
out.logsout
ans =
Simulink.SimulationData.Dataset 'logsout' with 3 elements Name BlockPath ____ ___________________________ 1 [1x1 Variable] x ShotPut/Sensing/6-DOF Joint 2 [1x1 Variable] y ShotPut/Sensing/6-DOF Joint 3 [1x1 Variable] z ShotPut/Sensing/6-DOF Joint - Use braces { } to access, modify, or add elements using index.

Design Study

With those changes done, I decided to study the impact of some parameters on the simulation results. For that, I can use the new Design Study introduced in R2024a.
First, I specified a variable shoulderAngle in the Rigid Transform block controlling the shoulder angle and marked it as Run-Time tunable, so I can tune it when the model is simulated in Fast Restart mode.
I created a design study with an array of 10 values from 45 degrees to 135 degrees.
ShoulderAngleVar = simulink.multisim.Variable("shoulderAngle", linspace(45,135,10));
d = simulink.multisim.DesignStudy(mdl,ShoulderAngleVar);
out = parsim(d,'ShowProgress','off','UseFastRestart','on');
figure
hold on
for i = 1:length(out)
    plot3(out(i).logsout.get('x').Values.Data,...
        out(i).logsout.get('y').Values.Data,...
        out(i).logsout.get('z').Values.Data)
end
view([-95.14 19.80])
axis equal

Now it's your turn

Don't miss the shot put events at the Paris Olympics:
Are you using the Upgrade Advisor when upgrading to new MATLAB releases? Are you taking advantage of the new features add to Simscape and Simulink? Have you tried the new Design Study? Let us know in the comments below.

]]>
https://blogs.mathworks.com/simulink/2024/07/31/shot-put-olympics-2024-update/feed/ 0
Derivative of state ‘1’ in block ‘X/Y/Integrator’ at time 0.55 is not finite https://blogs.mathworks.com/simulink/2024/07/22/derivative-of-state-1-in-block-x-y-integrator-at-time-0-55-is-not-finite/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2024/07/22/derivative-of-state-1-in-block-x-y-integrator-at-time-0-55-is-not-finite/#comments Mon, 22 Jul 2024 19:10:25 +0000 https://blogs.mathworks.com/simulink/?p=16659

Let's look at another frequently visited MATLAB Answers page:Derivative of state '1' in block 'X/Y/Integrator' at time 0.55 is not finite.The ProblemHere is a simple model similar to the one I have... read more >>

]]>
Let's look at another frequently visited MATLAB Answers page:

The Problem

Here is a simple model similar to the one I have been using recently in multiple posts.
mdl = "suspension";
open_system(mdl);
When simulating the model, we get the same error as reported in MATLAB Answers:
in = Simulink.SimulationInput(mdl);
in = in.setModelParameter('Stoptime','500');
in = in.setModelParameter('CaptureErrors','on');
out= sim(in);
out.ErrorMessage
ans = 'Derivative of state 'dx' in block 'suspension/Integrator, Second-Order' at time 284.04767405115081 is not finite. The simulation will be stopped. There may be a singularity in the solution. If not, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances)'
This error can be triggered by multiple reasons. Before diving into the reasons, I would like to highlight the tools that are the most likely to help you diagnose this type of issue.

Debugging Tools

Solver Profiler

Try simulating using the Solver Profiler, which you can launch from the Debug tab:
In the Explore Gallery, launch the States Explorer.
This will allow you to quickly scan all the states in the model and identify which states are diverging:

Highlight Source

Another useful tool is to Highlight Signal to Source the signal entering the block reported in the error message:
Once enabled, use the arrow keys to highlight the upstream blocks feeding the integrator and try understanding the logic making the equations unstable.

Simulink Debugger

The Simulink Debugger allows you to step block by block during a simulation, which can be useful to diagnose this kind of issue.
First, select the blocks upstream of the block listed in the error message and enable Port Value Display.
Select the signal entering the problematic block and add a breakpoint. You have the option to break on Inf or NaN, but I recommend breaking earlier to better observe what happens before the error.
Click Run and when the breakpoint is hit, you will be able to step block by block to try identifying the problem with the equations in your model.
Let's now look at the most common situations leading to this error.

Reason 1: Unstable System

The most common reason for this error is that equations in the model are unstable. This usually happens if the algorithm has been implemented incorrectly, or if you are simulating a system that is truly unstable.
It can be useful to plot the state mentioned in the error message to see that it diverges toward infinity:
plot(out.xout.get('dx').Values)
In this simulation, the size of the model makes it easy to identify the problem. Here is an animation where I enabled port value display for all blocks and I am slowly stepping the model forward so we can see the evolution of each signal. Notice how the values are increasing at each time step:
StepUnstableModel.gif
The implementation mistake here is that signs specified in the Sum block result in a positive feedback loop. To solve the problem and make this simulation behave as the mass-spring-damper it is trying to model, we need to make the signs of the feedback signals entering the Sum block negative.
in = Simulink.SimulationInput(mdl);
in = in.setBlockParameter('suspension/Sum','Inputs','+--');
out = sim(in);
plot(out.xout.get('dx').Values)

Reason 2: Step size is too large

As described in the error message, one possible reason for this error is the solver taking too large steps. This typically happens when using fixed-step solver, which is necessary to generate code and deploy to real-time systems.
Here is a slightly different version of the model.
mdl = "suspensionFixedStep";
open_system(mdl);
I fixed the signs of the Sum block to make the equations stable, but I changed the solver to ode3 with a step size of 1 second.
I will simulate the model with larger values for k and c, making the system dynamic fast and impossible to capture properly with the step sized of 1 seconds.
in = Simulink.SimulationInput(mdl);
in = in.setModelParameter('CaptureErrors','on');
in = in.setVariable('k',1e5);
in = in.setVariable('c',100);
out = sim(in);
out.ErrorMessage
ans = 'Derivative of state 'dx' in block 'suspensionFixedStep/Integrator, Second-Order' at time 49.5 is not finite. The simulation will be stopped. There may be a singularity in the solution. If not, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances)'
There are multiple ways to analyze the system and decide how to deal with this error.

Analysis 1: The Equations

A first approach is to analyze the equations in the model. This is obviously easier if the model is small. In this example, we have a mass-spring-damper system. The natural frequency of this system can be computed analytically using:
omega_n = sqrt(k/m)
omega_n = 223.6068
This means that the system will oscillate with a period of:
T = 2*pi/omega_n % oscillation period in seconds
T = 0.0281
To capture this oscillation accurately, we need at least a minimum number of points per oscillation.

Analysis 2: Linearization

Another approach to study the dynamics of the equations in your system is to linearize it using Simulink Control Design.
linsys = linearize(mdl);
We can then extract the natural frequency using damp. Thanks to MATLAB GPT for reminding me the existence of damp.
[wn, zeta, p] = damp(linsys);
T_lin = 2*pi/max(wn) % oscillation period in seconds
T_lin = 0.0281

Analysis 3: Variable-Step Solver

When getting this error with a fixed-step solver, one option is simulating the model with a variable-step solver. First, this gives you a good reference in terms of accuracy.
in = Simulink.SimulationInput(mdl);
in = in.setModelParameter('SolverType','Variable-step');
in = in.setModelParameter('StopTime','0.2');
in = in.setVariable('k',1e5);
in = in.setVariable('c',100);
outVarStep = sim(in);
figure
plot(outVarStep.xout.get('dx').Values);
Second, seeing what time steps the variable-step solver is taking can be useful to pick a fixed step-size. The Solver Profiler has a Step Size plot that can help with that. In this case, we can see that the variable-step solver needs to take steps slightly smaller than 0.01 second.
Once you better understand the system dynamic, it's time to look into solutions.

Solution 1: Smaller step-size

Let's try simulating the model with different fixed-step size and see what the results look like.
ts = [0.0005 0.001 0.002 0.005 0.01];
clear in
in(1:length(ts)) = Simulink.SimulationInput(mdl);
for i = 1:length(ts)
    in(i) = in(i).setModelParameter('FixedStep',num2str(ts(i)));
    in(i) = in(i).setModelParameter('StopTime','0.2');
    in(i) = in(i).setVariable('k',1e5);
    in(i) = in(i).setVariable('c',100);
end
out = sim(in,'ShowProgress','off');
Looking at the results, we can see that they become less and less accurate as the step size increase. If simulated for a larger stop time, the last step size of 0.01 would eventually error out with the infinite derivative error.
figure;hold on
plot(outVarStep.xout.get('dx').Values,'linewidth',2);
for i = 1:length(ts)
    plot(out(i).xout.get('dx').Values)
    legendLabel{i} = ['Ts = ' num2str(ts(i))]; %#ok<SAGROW>
end
axis([0 0.2 -2e-3 2e-3])
legend([ 'Variable-Step' legendLabel]);

Solution 2: Use a different solver

The solver being used can also impact the accuracy of the results. The higher the order, the more computationally expensive, but also the more accurate a solver is.
solvers = {'ode1','ode3','ode5','ode1be'};
clear in
in(1:length(solvers)) = Simulink.SimulationInput(mdl);
for i = 1:length(solvers)
    in(i) = in(i).setModelParameter('FixedStep','0.005');
    in(i) = in(i).setModelParameter('StopTime','0.5');
    in(i) = in(i).setModelParameter('Solver',solvers{i});
    in(i) = in(i).setVariable('k',1e5);
    in(i) = in(i).setVariable('c',100);
end
out = sim(in,'ShowProgress','off');
Here we can see that ode1 is unstable while ode5 gives results close to the variable-step solver. Ode1be is an implicit solver that is especially good at remaining stable when solving stiff systems.
figure;hold on
plot(outVarStep.xout.get('dx').Values,'linewidth',2);
for i = 1:length(solvers)
plot(out(i).xout.get('dx').Values)
end
axis([0 0.2 -2.5e-3 2.5e-3])
legend([' Variable-Step' solvers]);

Solution 3: Modify the system dynamics

In some cases, real-time constraints can make it impossible to use a larger step-size or a more accurate solver. In such case, the solution is most likely to try simplifying the system equations or to soften the dynamics.
The Simscape documentation has an extensive section on techniques to adapt a model for real-time simulation: Real-Time Simulation. Many of those techniques are not Simscape-specific and also apply to any Simulink model.

Division by Zero

This one might sound obvious, but if the equations in the model return Inf and this Inf is passed to an Integrator block, you will get this error. One common reason for that is a division by zero.
mdl = "example3";
open_system(mdl);
in = Simulink.SimulationInput(mdl);
in = in.setModelParameter('CaptureErrors','on');
out = sim(in);
out.ErrorMessage
ans = 'Derivative of state '1' in block 'example3/Integrator' at time 0.89047195013357083 is not finite. The simulation will be stopped. There may be a singularity in the solution. If not, try reducing the step size (either by reducing the fixed step size or by tightening the error tolerances)'
To diagnose this, I recommend using the Simulink Debugger. Setting a breakpoint on Inf or NaN will stop the simulation at the first block where the Inf is generated.
In this case, the solution is to modify the equations to avoid feeding Inf to Integrator blocks.

Now it's your turn

Have you run into problems with infinite derivative error? Let us know in the comments below.

]]>
https://blogs.mathworks.com/simulink/2024/07/22/derivative-of-state-1-in-block-x-y-integrator-at-time-0-55-is-not-finite/feed/ 7
How to Run Simulink Simulation from MATLAB Script? https://blogs.mathworks.com/simulink/2024/06/26/how-to-run-simulink-simulation-from-matlab-script/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2024/06/26/how-to-run-simulink-simulation-from-matlab-script/#comments Wed, 26 Jun 2024 21:02:28 +0000 https://blogs.mathworks.com/simulink/?p=16511

I recently ran into a report of the most visited entries on MATLAB Answers. I looked at the ones involving Simulink and thought it would be interesting to cover some of those on this blog. While most... read more >>

]]>
I recently ran into a report of the most visited entries on MATLAB Answers. I looked at the ones involving Simulink and thought it would be interesting to cover some of those on this blog.
While most questions have direct answers, I think this is a good opportunity to provide additional background and cover some subtleties not addressed on MATLAB Answers.
This week, I am starting with the most visited:
Before giving you my answer to this question, I want to encourage you to visit the documentation page Run Simulations Programmatically. It covers in details into all the options available and their implications.
Now, let's go with my shorter informal version.
To me, simulating a model programmatically boils down to the four following options:
  • Sim with model name: Passing the model name to the sim command. It's simple and works for many use cases.
  • Sim with Simulation Input object: Passing a Simulink.SimulationInput object to the sim command. The most versatile and scalable approach.
  • Simulation object: Introduced in R2024a, the Simulation object provides an interface to control the simulation execution: start, step, stop and tune parameters
  • Old and Discouraged: Older syntaxes that are still available for backward compatibility, but that you should avoid

Sim with Model Name

If you have a Simulink model that simulates using the Run button, the quickest and simplest way to simulate it from MATLAB is probably to call the sim command and pass it the model name.
For example, I have a model saved as suspension.slx.
mdl = 'suspension';
open_system(mdl)
I can simulate it by first defining the data it needs in the MATLAB workspace and then calling sim:
out = sim(mdl)
out =
Simulink.SimulationOutput: logsout: [1x1 Simulink.SimulationData.Dataset] tout: [1003x1 double] yout: [1x1 Simulink.SimulationData.Dataset] SimulationMetadata: [1x1 Simulink.SimulationMetadata] ErrorMessage: [0x0 char]
All the logged data is contained within the variable out, which is a Simulink.SimulationOutput object. For example, if I want to plot the velocity computed by the Integrator block, I can execute:
plot(out.yout.get('dx').Values)
If you try this with your model and sim returns a vector instead of a Simulation Output object, see the Old and Discouraged section below.

Sim with Simulation Input object

While the above approach works in many cases, I recommend a slightly different approach. As described by Reid Spence in this comment, specifying a Simulink.SimulationInput object and passing it to the sim command offers a lot of advantages:
  • Explicitly specify variables, signals, states and parameters used for the simulation
  • Straightforward transition to parallel simulations using parsim, batchsim and Simulink Compiler
I expect that additional features to be released in future versions of Simulink will also be based on use of the Simulation Input object, so I encourage you to start using it today.
In its simplest form, using a Simulation Input object adds only one line of code to the previous approach:
in = Simulink.SimulationInput(mdl)
in =
SimulationInput with properties: ModelName: 'suspension' InitialState: [0×0 Simulink.op.ModelOperatingPoint] ExternalInput: [] ModelParameters: [0×0 Simulink.Simulation.ModelParameter] BlockParameters: [0×0 Simulink.Simulation.BlockParameter] Variables: [0×0 Simulink.Simulation.Variable] PreSimFcn: [] PostSimFcn: [] UserString: '' VariantConfiguration: ''
You can then pass this to the sim command:
out = sim(in);
The main advantage of the Simulation Input object is that it explicitly specifies what is being passed to the sim function. For example, let's modify the previously created object by specifying:
  • A different stop time:
in = in.setModelParameter('StopTime','20');
  • A different value for the variable k:
in = in.setVariable('k',20);
  • A signal for the root-level Inport block:
ds = createInputDataset(mdl);
ds{1} = timeseries([0 0 1 1],[0 10 10 20]);
in = in.setExternalInput(ds);
  • The initial states of the Integrator block:
x0 = Simulink.BlockDiagram.getInitialState(mdl);
x0{1}.Values.Data(2) = 0.1;
in = in.setInitialState(x0);
I can then simulate the model and plot the results:
out = sim(in);
plot(out.yout.get('dx').Values)

Simulation object

In R2024a, we introduced the Simulation object. This object allows you to programmatically start, pause, step and tune block parameters in the same way as you would do while interacting with the Simulink editor.
Here is an example that runs the simulation between 0 and 5 seconds with variable c set to 0, and then runs it between 5 and 10 seconds with c equal to 10:
sm = simulation(mdl);
setVariable(sm,'c',0);
step(sm,PauseTime=5);
setVariable(sm,'c',10);
step(sm,PauseTime=10);
out = stop(sm);
plot(out.yout.get('dx').Values);

Old and Discouraged

At this point, I need to cover approaches that we want to discourage. We are providing those for backward compatibility, but we discourage using them because they come with many limitations and usability issues.
If you see one of those being used, I strongly encourage you to convert your code to use the Simulation Input object as described above.
In R2009b, we introduced the Single simulation output option.
Programmatically, this option can be disabled using:
set_param(mdl,'ReturnWorkspaceOutputs','off');
Once this is done, you can call the sim command without output arguments:
sim(mdl)
Once the simulation complete, you will see the individual parameters specified in the Data Import/Export section of the configset magically appear in the MATLAB base workspace.
logsout
logsout =
Simulink.SimulationData.Dataset 'logsout' with 2 elements Name BlockPath _____ __________________ 1 [1x1 Signal] accel suspension/1//mass 2 [1x1 Signal] F suspension/Sum - Use braces { } to access, modify, or add elements using index.
Another even older syntax that still exists only for backward incompatibility is this one, where the sim command returns 3 outputs for time, states, and outputs:
[t,x,y] = sim(mdl);
Once again, I recommend avoiding those and use the Simulation Input object instead.

Other Considerations

Running Multiple Simulations

If you are planning to run multiple simulations, I recommend creating an array of Simulation Input object and passing it to the sim command. Let's run our example for multiple damping values:
% Setup an array of SimulationInput objects
in(1:5) = Simulink.SimulationInput(mdl);
for i = 1:length(in)
in(i) = in(i).setVariable('c',i);
end
% Simulating
out = sim(in,'ShowProgress','off');
% Visualizing results
figure;hold on
for i = 1:length(out)
plot(out(i).yout.get('dx').Values);
end
To run this code in parallel, all you need to do is replace the call to sim with parsim or batchsim.

Best Practice for Data Management

Simulations can be launched from multiple contexts: MATLAB Scripts, MATLAB Functions, MATLAB Classes, App Designer apps, etc. For your model to be easily run from any context, I recommend associating with your model a set of default values for all the parameters. This is typically done in two ways:
For more details on this topic, I recommend visiting: Determine Where to Store Variables and Objects for Simulink Models.
With that setup, it makes it easy to simply open the model and hit Ctrl+D to do an update diagram, or click Run to simulate it without the need to run any code. This also makes it easy to run functions like Simulink.BlockDiagram.buildRapidAcceleratorTarget or slbuild.
When times come to simulate the model, you can create Simulation Input objects to specify the data that needs to change from the default values associated with the model as illustrated above.

Now it's your Turn

Have you adopted the Simulink.Simulation object? What's your preferred way to run simulations from MATLAB? Which challenges are you encountering when simulating models form MATLAB?
Let us know in the comments below.
]]>
https://blogs.mathworks.com/simulink/2024/06/26/how-to-run-simulink-simulation-from-matlab-script/feed/ 12
What’s New in Simulink R2024a? https://blogs.mathworks.com/simulink/2024/04/11/whats-new-in-simulink-r2024a/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2024/04/11/whats-new-in-simulink-r2024a/#comments Thu, 11 Apr 2024 15:35:41 +0000 https://blogs.mathworks.com/simulink/?p=16392

MATLAB R2024a is now available, and a lot of new important features have been added to Simulink. Here are my top 5.Simulation objectUsing the Simulation object, you can programmatically run a... read more >>

]]>
MATLAB R2024a is now available, and a lot of new important features have been added to Simulink. Here are my top 5.

Simulation object

Using the Simulation object, you can programmatically run a simulation step by step. You can execute the simulation one step at a time, for a specified number of steps or up to a specific time. Here is an example where I simulate the model up to t=18.5 seconds, then I change the value of variable k and continue the simulation until the stop time:
mdl = 'vdpX';
sm = simulation(mdl);
% Run the first part of the simulation with k=0.2
sm.setVariable('k',0.2);
step(sm,PauseTime=18.5);
% Run the second half with k=1.5
sm.setVariable('k',1.5);
step(sm,PauseTime=40);
out = terminate(sm);

Design Study

The new Design Study API provides a layer on top of parsim and batchsim to improve scalability. Instead of creating an array of Simulink.SimulationInput objects, you specify arrays of values to be simulated, and how they should be combined. Here is a simple example where I simulate a mass-spring-damper system for different mass and damping values.
I specify 5 mass values and 5 damping values, and simulate an exhaustive combination for a total of 25 simulation
mdl = 'simple_system';
kVar = simulink.multisim.Variable('c',1:5);
cVar = simulink.multisim.Variable('m',1:5);
fullSpace = simulink.multisim.Exhaustive([kVar cVar]);
myDesignStudy = simulink.multisim.DesignStudy(mdl, fullSpace);
outH = parsim(myDesignStudy,'ShowProgress','Off','UseFastRestart','on');
out = fetchOutputs(outH);

Specifying Variant Configurations using a SimulationInput object

A new VariantConfiguration property has been added to the Simulink.SimulationInput object. Here is an example code where I get the variant configuration data for a model and run one simulation per available configuration:
mdl = 'sldemo_variant_subsystems';
load_system(mdl);
load('variantConfigs.mat'); % load pre-saved variant configuration data
vcd = Simulink.VariantManager.getConfigurationData(mdl);
N = length(vcd.Configurations);
in(1:N) = Simulink.SimulationInput(mdl);
for i = 1:N
in(i) = in(i).setVariantConfiguration(vcd.Configurations(i).Name);
end
out = sim(in,'ShowProgress','off');

Simplified Mechanism to access Data Dictionaries

Before R2024a, if you wanted to programmatically change the value of a parameter stored in a data dictionary, you had to write code like this:
myDictionaryObj = Simulink.data.dictionary.open('simplesystemDD.sldd');
dDataSectObj = getSection(myDictionaryObj,'Design Data');
kObj = getEntry(dDataSectObj,'k');
k = getValue(kObj);
k = k+1;
setValue(kObj,k);
In R2024a, you can simple connect to a data dictionary and interact with it using the dot operator.
h = Simulink.data.connect('simplesystemDD.sldd');
h.k = h.k+1;

Preserve alignment when moving and resizing blocks

Let's close this list with a simple quality-of-life editing improvement. This is not a game-changer like some of the previous highlights but will hopefully improve your editing experience.
When selecting a block, you might notice a light green highlighting on connections and blocks around it. This means that we have detected that those connections and blocks should likely move with the blocks.
MoveBlocks.gif
Same works with resizing:
ResizeBlocks.gif

Now it's your turn

Have a look at the Simulink release notes for R2024a. Let us know your favorite feature and which ones you would like to see highlighted on this blog.
]]>
https://blogs.mathworks.com/simulink/2024/04/11/whats-new-in-simulink-r2024a/feed/ 4