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. Thu, 14 Mar 2024 12:38:22 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.2 Computing π… Simscape Multibody Style https://blogs.mathworks.com/simulink/2024/03/14/computing-%cf%80-simscape-multibody-style/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2024/03/14/computing-%cf%80-simscape-multibody-style/#comments Thu, 14 Mar 2024 07:14:38 +0000 https://blogs.mathworks.com/simulink/?p=16135

On this π day 2024, I decided to tag along with Mike Croucher from The MATLAB Blog and show one way to compute π.While Mike went for advanced maneuvers involving the MATLAB AI Chat Playground,... read more >>

]]>
On this π day 2024, I decided to tag along with Mike Croucher from The MATLAB Blog and show one way to compute π.
While Mike went for advanced maneuvers involving the MATLAB AI Chat Playground, Parallel Computing Toolbox, and even Quantum Computing, I decided to go with the way our ancestors would have done thousands of years ago: by rolling a cylinder. See method 1 in this WikiHow article for more details.

The Model

Using Simscape Multibody, I connected a Planar Joint and a Cylinder Solid together. I let the Cylinder fall on an Infinite Plane and used the Spatial Contact Force block to compute the contact dynamic between those two:
mdl = 'ComputePi';
open_system(mdl);
I used Motion Actuation to roll the cylinder by 360 degrees and sensed by how much it had translated. I was then able to compute π using:
π=d2r
where d is the distance travelled and r is the radius of the cylinder.
in = Simulink.SimulationInput(mdl);
out = sim(in);
r = 1; % Cylinder radius;
d = out.yout{1}.Values.Data(end); % final distance
pi_estimate = d/(2*r)
pi_estimate = 3.0956
Because the cylinder slipped a bit on the ground, I did not get a very accurate result, but it's probably representative of the result you would get if you had tried computing π that way a few thousand years ago.
Here is the Mechanics Explorer animation for this simulation:
RollingCylinder.gif

Now it's your turn

Hopefully, you can find more accurate ways to compute π.
If you need to model cylinders rolling on the ground, try opening the model used for this blog post in MATLAB Online by clicking on this banner:
]]>
https://blogs.mathworks.com/simulink/2024/03/14/computing-%cf%80-simscape-multibody-style/feed/ 1
Become a MathWorks Certified Simulink Associate! https://blogs.mathworks.com/simulink/2024/01/10/become-a-mathworks-certified-simulink-associate/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2024/01/10/become-a-mathworks-certified-simulink-associate/#respond Thu, 11 Jan 2024 00:45:06 +0000 https://blogs.mathworks.com/simulink/?p=16112

The MathWorks Certification Program recently released a new certification: Simulink Associate.With this certification, you will be able to demonstrate your Simulink proficiency to colleagues,... read more >>

]]>
The MathWorks Certification Program recently released a new certification: Simulink Associate.
With this certification, you will be able to demonstrate your Simulink proficiency to colleagues, industry peers and potential employers.
We carefully designed the certification such that it validates the skills most organizations seek in successful and productive Simulink users.

How to become a MathWorks Certified Simulink Associate

To be certified, you will need to register and pass an online test with 42 multiple-choice questions. If you want to get a feeling of what those questions look like, see the sample exam questions. Here is one example:
Before taking the test, I also recommend looking at the list of topics covered in the test. This will help you determine if you need to learn new features and maybe sign up for training before taking the test.

How to showcase your certification

Once you are done, you will be able to show off your achievement through a digital credential. Anyone earning the certification will receive this credential through Credly, which can then be shared with employers or on your LinkedIn profile.

Now it's your turn

Give a look at the exam information and recommended preparation on the MathWorks Certification Program page and register for the certification once you think you are ready.
]]>
https://blogs.mathworks.com/simulink/2024/01/10/become-a-mathworks-certified-simulink-associate/feed/ 0
How to Create a Mask Popup Parameter that can be tuned in Rapid Accelerator https://blogs.mathworks.com/simulink/2023/11/01/how-to-create-a-mask-popup-parameter-that-can-be-tuned-in-rapid-accelerator/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2023/11/01/how-to-create-a-mask-popup-parameter-that-can-be-tuned-in-rapid-accelerator/#respond Wed, 01 Nov 2023 17:16:16 +0000 https://blogs.mathworks.com/simulink/?p=16013

A few weeks ago I published this blog post: Getting the most out of Rapid Accelerator mode – Version R2023b, where I described how to simulate a model multiple times in Rapid Accelerator mode for... read more >>

]]>
A few weeks ago I published this blog post: Getting the most out of Rapid Accelerator mode – Version R2023b, where I described how to simulate a model multiple times in Rapid Accelerator mode for maximum performance using the parameter RapidAcceleratorUpToDateCheck='off'.
In this previous post, I was tuning the value of a Gain block. This week I received the question: Can I do the same for a parameter of type popup?

The Problem

I have this model with a masked subsystem that has a popup parameter. Under the mask, the variable associated with the popup, choice, is used to control what type of noise is added to the signal:
If I try to simulate the model as described in the previous blog post, I get an error saying that it's not possible to use setBlockParameters and RapidAcceleratorUpToDateCheck='off' at the same time:
mdl = 'testNoise';
blk = [mdl '/AddNoise'];
in(1:3) = Simulink.SimulationInput(mdl);
for i = 1:3
in(i) = in(i).setModelParameter(SimulationMode='Rapid');
in(i) = in(i).setModelParameter(RapidAcceleratorUpToDateCheck='off');
end
try
in(1) = in(1).setBlockParameter(blk,'choice','Random');
catch ME
ME.message
end
ans = 'Cannot set 'BlockParameters' on SimulationInput object when 'RapidAcceleratorUpToDateCheck' is set to 'off'.'

The Solution

The solution to this is described in the documentation page Tune Mask Enumeration Parameters - Popup and Radio Button. I find this page is a bit long and complex, so I will try to summarize the process here.
The first thing you need to do is associate an enumeration with the popup parameter. For this example, the enumeration is:
classdef noise < Simulink.Mask.EnumerationBase
enumeration
Random (1,'Random')
Pulse (2,'Pulse')
Sequence (3,'Sequence')
end
end
I then associate it with the parameter in the Mask Editor by double-clicking on the Type options field:
In the Subsystem under the mask, I need to modify how the variable is specified in the block dialog. For this example, instead of using the variable choice directly, I need to specify noiseValues(choice). The documentation explains the syntax, but in short you begin with the enumeration name (noise in this example) and you append "Values" to it. Then you pass to it, between parenthesis, the popup variable (choice in this example):
If you create the masked Subsystem that way, you will notice that the dialog has a new "Associate Variable" option:
This will open a dialog to specify the variable and optionally create it if it does not exist. For this example, I will create it myself:
noiseType = noise.Random;
Once you click ok, in the block dialog, you will see the variable name and the enumeration type next to it:
And that's it, now it's time to simulate the model:
mdl = 'testNoiseTunable';
in(1:3) = Simulink.SimulationInput(mdl);
for i = 1:3
in(i) = in(i).setModelParameter(SimulationMode='Rapid');
in(i) = in(i).setModelParameter(RapidAcceleratorUpToDateCheck='off');
end
in(1) = in(1).setVariable('noiseType',noise.Random);
in(2) = in(2).setVariable('noiseType',noise.Pulse);
in(3) = in(3).setVariable('noiseType',noise.Sequence);
out = sim(in,'ShowProgress','off');
Once the simulation completes, we can plot the results and confirm that the parameter has been tuned:
plot(out(1).yout{1}.Values);
hold on
plot(out(2).yout{1}.Values);
plot(out(3).yout{1}.Values);
hold off
legend({'Random','Pulse','Sequence'});

Now it's your turn

If you are creating masked library blocks with parameters of type popups, be nice to your users and associate the popup with an enumeration type. This will enable them to tune it in Rapid Accelerator optimally. This will also enable the parameter to be tuned if the model is deployed with Simulink Compiler.
]]>
https://blogs.mathworks.com/simulink/2023/11/01/how-to-create-a-mask-popup-parameter-that-can-be-tuned-in-rapid-accelerator/feed/ 0
Accelerator Cache and Rebuilds – Everything you need to know https://blogs.mathworks.com/simulink/2023/10/18/accelerator-cache-and-rebuilds-everything-you-need-to-know/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2023/10/18/accelerator-cache-and-rebuilds-everything-you-need-to-know/#comments Wed, 18 Oct 2023 15:55:57 +0000 https://blogs.mathworks.com/simulink/?p=15893

In Simulink, the different simulation modes (accelerators) can save you a lot of time. There are, however, subtleties to what “time” you can save, and how we can achieve those savings. In this post,... read more >>

]]>
In Simulink, the different simulation modes (accelerators) can save you a lot of time. There are, however, subtleties to what “time” you can save, and how we can achieve those savings. In this post, I will explain most of the cases you can encounter, and hopefully shed light on what simulation modes and options best align with your needs.
First, let me introduce the way I think about the main phases that take time when simulating a model involving any of the accelerator modes:
If you start from scratch, without any existing cache, Simulink will do all 3 of those phases. However once you simulate the model, a Simulink Cache file gets created and can be reused for subsequent simulations.
On the above timeline, what I spend the most time explaining is the multiple subtleties that can cause the Checksum Analysis and Accelerator Target Generation to happen or not. I will try to summarize that here.
There are differences for the three accelerator targets:
  • Top level Accelerator mode
  • Rapid Accelerator mode
  • Referenced models Accelerator mode
Let's look at each of them on by one.

Top Level Accelerator mode

As described here, in most cases, Accelerator mode uses Just-in-Time (JIT) acceleration to generate an execution engine in memory.
Let's take a simple model and simulate it in Accelerator mode with verbose build enabled.
mdl = 'vdp';
in = Simulink.SimulationInput(mdl);
in = setModelParameter(in,'SimulationMode','Accelerator');
in = setModelParameter(in,'AccelVerboseBuild','on');
out = sim(in);
If this is the first time you are simulating the model in a MATLAB session, 3 things can happen:

1 - No Cache Available

If no cache is available or if the model has changed structurally since the last time the cache file was generated, Simulink will perform the checksum analysis and generate the accelerator target. Artifacts will be stored in the cache file to be reused in subsequent simulations.
From the verbose build, you will see the following:

2 - Cache is available

If a cache is available and the model has not changed structurally since the cache was built, Simulink will extract information that will make the generation of the execution engine faster. Verbose build will display the following:

3 - Subsequent Runs

After simulating the model once, the accelerator mode execution engine will remain in memory. If the model has not changed structurally, nothing will be displayed in the verbose log.
In this case, for Accelerator mode, our timeline is reduced to those two phases:

Fast Restart

In the previous cases, Simulink had to analyze the model to detect if the accelerator execution engine needed to be rebuilt or not due to structural changes. For large models, this operation can take a non-negligible amount of time.
If you know that you will simulate the model multiple times without making structural changes, I recommend enabling Fast Restart.
With Fast Restart, after simulating, the model will remain in a compiled state, making editing impossible between runs. This reduces the initialization time (time spent in the first two phases) to practically zero. This reduces our timeline to only the execution phase:

Rapid Accelerator

Rapid Accelerator works differently. As described here, Rapid Accelerator generates a standalone executable:
Let’s go through the 3 possible scenarios and what happens in each:

1 - No cache available, or cache is out of date

In Rapid Accelerator, a Build Summary is displayed, either in the Diagnostics Viewer if simulated using the play button, or at the MATLAB command prompt if using the sim command.
mdl = 'vdp';
in = Simulink.SimulationInput(mdl);
in = setModelParameter(in,'SimulationMode','Rapid');
out = sim(in);
If no cache exists, the build summary will say:
If a cache file exists but is out of date, the build summary will include the reason why it rebuilds:
In this case, Simulink went through the entire timeline.

2 - Cache is available

If a cache file exists and no structural changes have happened to the model sine the cache was built, you will see:
In this case, our timeline is:

3 - RapidAcceleratorUpToDateCheck

For Accelerator mode, I recommended using Fast Restart to skip the checksum analysis phase that decides if the accelerator target needs to be rebuilt. Fast Restart is not supported in Rapid Accelerator, but there is something you can do to skip the checksum analysis phase in this mode. For that, you can pass the option RapidAcceleratorUpToDateCheck to the sim command:
mdl = 'vdp';
in = Simulink.SimulationInput(mdl);
in = setModelParameter(in,'SimulationMode','Rapid');
in = setModelParameter(in,'RapidAcceleratorUpToDateCheck','off');
out = sim(in);
With this option, there is no build summary, because it is 100% sure that there will be no build.
One important difference compared to Accelerator mode with Fast Restart is that the RapidAcceleratorUpToDateCheck option can be used for the first simulation in a MATLAB session if a cache file is available.
Coming back to our timeline, this option performs the execution phase only.

Referenced Model in Accelerator Mode

A referenced model in Accelerator mode is different than the two use cases above. First, the simulation mode is controlled from the Model block dialog or Property Inspector:
If you choose Accelerator mode, C code is being generated for the referenced model and compiled as a MEX-file. This offers a finer grain control when it comes to rebuild options.
If you look at the Model Referencing section of the Configuration set, you will see 4 options:
To learn more about those options, I recommend looking at this documentation page. Specifically, this diagram:
Here is how I interpret this diagram and the 4 rebuild options:
  • Always: This one is straightforward. Every time you simulate the model, Simulink ignores the cache, regenerate the accelerator target code and builds it. This is the most time consuming, and you get the full timeline:
  • If changes detected: This option is the safest way to avoid unnecessary rebuilds. Simulink will do a checksum analysis every time you simulate the model and regenerate code if a structural change is detected.
  • If changes in known dependencies detected: This option is usually the best tradeoff between safety and performance. Simulink will first look at the timestamp of the model and known dependencies and if they have not changed since the cache was built, the cache will be used. If Simulink detects that the model or known dependencies have a timestamp more recent that the cache, then a checksum analysis is triggered to determine if code needs to be regenerated. If a structural change is detected, code will be generated and rebuilt. The downside of this option is that some dependencies might be unknown, see the known dependencies documentation for more details on that. If the model has not changed structurally, our timeline can be one of those two. I describe below how to determine which one is happening for your model.
  • Never: This option is similar in nature to the RapidAcceleratorUpToDateCheck option for Rapid Accelerator mode. Simulink will close its eyes and blindly use the cache. This option comes with a diagnostic to detect if the cache should have been rebuilt. Setting this diagnostic to "None" is what will give you the fastest performance. Here is a screenshot:
Configured that way, we get the fastest timeline:
I have to admit, the command-line equivalents of the rebuild options are quite different sounding than the graphical version. To help with that, here is a table:
To get a clear understanding of what happened, I recommend enabling the accelerator verbose build.
mdl = 'sldemo_mdlref_basic';
in = Simulink.SimulationInput(mdl);
in = setModelParameter(in,'UpdateModelReferenceTargets','IfOutOfDate');
in = setModelParameter(in,'AccelVerboseBuild','on');
out = sim(in);
In this case, I am using "If changes in known dependencies detected" and I have a cache file available. However, I made a minor non-structural change to the referenced model. The build log tells us that it checks for structural change, does not find any and consequently does not regenerate code.
If I rerun the same code, but this time without any modification to the referenced model, the check for structural changes is skipped, which can speed up the initialization significantly:

Now it's your turn

Hopefully the above information will help you getting the best performance out of your simulations involving accelerator modes. Let us know in the comments below how you are leveraging those options.
If your model is triggering checksum analysis and rebuilds more often than you think it should, reach out to technical support and we can help you with that.
]]>
https://blogs.mathworks.com/simulink/2023/10/18/accelerator-cache-and-rebuilds-everything-you-need-to-know/feed/ 4
YouTube Livestream on Speeding Up Simulink Simulation Workflows https://blogs.mathworks.com/simulink/2023/10/12/youtube-livestream-on-speeding-up-simulink-simulation-workflows/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2023/10/12/youtube-livestream-on-speeding-up-simulink-simulation-workflows/#respond Thu, 12 Oct 2023 16:30:43 +0000 https://blogs.mathworks.com/simulink/?p=15344

I don’t usually publicize this sort of thing on this blog, but I think the subject is too relevant for many readers of this blog to no advertise it. Next Thursday, October 19th, 2023, we are... read more >>

]]>
I don’t usually publicize this sort of thing on this blog, but I think the subject is too relevant for many readers of this blog to no advertise it.

Next Thursday, October 19th, 2023, we are having a YouTube Livestream on speeding up Simulink simulations!

With my colleagues Weiwu and Reid, we will share the most useful tips and tricks we have gathered through many years of supporting Simulink users.

Click the "Notify me" button on the YouTube page if you don't want to forget.

For those who cannot wait, I recommend looking at the article Improving Simulation Performance in Simulink that Weiwu, Reid, and I published earlier this year.

Improving simulation performance in Simulink

This should give you an idea of the type of tips and tricks we are planning to cover during the live stream.

]]>
https://blogs.mathworks.com/simulink/2023/10/12/youtube-livestream-on-speeding-up-simulink-simulation-workflows/feed/ 0
Getting the most out of Rapid Accelerator mode – Version R2023b https://blogs.mathworks.com/simulink/2023/10/05/getting-the-most-out-of-rapid-accelerator-mode-version-r2023b/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2023/10/05/getting-the-most-out-of-rapid-accelerator-mode-version-r2023b/#comments Thu, 05 Oct 2023 20:57:08 +0000 https://blogs.mathworks.com/simulink/?p=15317

Earlier this week, a user came to me with a question related to a blog post I wrote a long time ago: Getting the most out of Rapid Accelerator mode. This made me realize that since then, we have made... read more >>

]]>
Earlier this week, a user came to me with a question related to a blog post I wrote a long time ago: Getting the most out of Rapid Accelerator mode. This made me realize that since then, we have made significant usability improvements to this workflow. This inspired me to rewrite this blog post using the latest recommended syntax as of MATLAB R2023b.

Rapid Accelerator

As explained here, the Rapid Accelerator simulation mode can speed up simulation by generating an executable for your model. The speedup can vary between models and for various reasons. Personally, I have seen some models run more than 10 times faster in Rapid Accelerator mode.

RapidAcceleratorUpToDateCheck = off

When you click the play button in a model or use the sim command, Simulink checks if your model has changed or not since the last simulation. If the model has not changed structurally, the Rapid Accelerator executable is not re-generated. Obviously, verifying if the model has changed requires some work and can take a non-negligible amount of time for large models.
To help with that, Rapid Accelerator has an option to skip this check and directly use the already existing executable, if one already exists.
Let's see how this can be done using a simple demo like sldemo_bounce. For this example, we will vary the coefficient of restitution, specified by variable k used in a Gain block.
Let's define a vector of coefficients we want to simulate for:
k_values = [-0.9:0.1:-0.1];
Then we create a vector of Simulink.SimulationInput objects that will tell Simulink to:
  • Simulate the model in Rapid Accelerator mode
  • Skip the up-to-date check
  • Run one simulation per coefficient of restitution value
mdl = 'sldemo_bounce';
in(1:length(k_values)) = Simulink.SimulationInput(mdl);
for i = 1:length(k_values)
in(i) = in(i).setModelParameter('SimulationMode','Rapid');
in(i) = in(i).setModelParameter('RapidAcceleratorUpToDateCheck','off');
in(i) = in(i).setVariable('k',k_values(i));
end
And that's it, we can simulate the model for all those values:
out = sim(in,'ShowProgress','off');
(Note: If you want the simulations to be executed in parallel, you can simply replace sim with parsim)
At the end, an array of Simulink.SimulationOutput objects is generated, from which we can extract and plot the results of each simulation.
for i = 1:length(out)
plot(out(i).logsout.get('Position').Values)
hold on;
end

What if I modified the model?

I mentioned it before, but I want to emphasize it here: With the RapidAcceleratorUpToDateCheck option set to off, Simulink will not check if your model has changed. It's up to you to tell Simulink to verify if the model has changed and to rebuild it if needed using Simulink.BlockDiagram.buildRapidAcceleratorTarget.
In this case, I have not modified the model, so Simulink.BlockDiagram.buildRapidAcceleratorTarget does not rebuild it and informs me that it was already up to date.
Simulink.BlockDiagram.buildRapidAcceleratorTarget(mdl);
Build Summary 0 of 1 models built (1 models already up to date) Build duration: 0h 0m 0.87016s

Now it's your turn

Give that a try and let us know what you think by leaving a comment below.
]]>
https://blogs.mathworks.com/simulink/2023/10/05/getting-the-most-out-of-rapid-accelerator-mode-version-r2023b/feed/ 2
Signals vs Parameters in Simulink… and the Parameter Writer block https://blogs.mathworks.com/simulink/2023/09/27/signals-vs-parameters-in-simulink-and-the-parameter-writer-block/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2023/09/27/signals-vs-parameters-in-simulink-and-the-parameter-writer-block/#comments Wed, 27 Sep 2023 17:07:04 +0000 https://blogs.mathworks.com/simulink/?p=15292

A colleague recently told me that he was often referring users to this blog post I wrote many years ago: How Do I Change a Block Parameter Based on the Output of Another Block?Even if most of what I... read more >>

]]>
A colleague recently told me that he was often referring users to this blog post I wrote many years ago: How Do I Change a Block Parameter Based on the Output of Another Block?
Even if most of what I wrote in that post still holds today, I thought it would be a good idea to revisit this topic and describe how the Parameter Writer block modifies the game.
Signals vs Parameters in Simulink
In How Do I Change a Block Parameter Based on the Output of Another Block?, I tried to explain something fundamentally different between MATLAB and Simulink. In general, in MATLAB, all the data you create and operate on is stored in variables. You double-click on entries in the Workspace Browser, it opens the Variable Viewer to show the value:
In Simulink there are two types of data:
  • Signals: Represented by signal lines in the Simulink canvas, this type of data is expected to potentially change at every time step
  • Parameters: Passed to Simulink blocks as MATLAB variables, this type of data is intended to remain constant or changes infrequently.
In many simple cases, the math ends up being the same. For example, using a Sum block to add two signals gives the same results as using a Bias block if its parameter has the same value as the equivalent signal fed to the Sum block. In other words, those 3 are the same:
This raises the question: Why can I not make any block dialog parameter an input signal?
My explanation is that some block algorithms are making assumptions that parameters will change infrequently. Changing those at every time step would lead to results that could be difficult to understand, or completely wrong depending on your assumptions.
In the next two sections, I describe how to tune the value of dialog parameters for situations where this is appropriate, and I give one example where doing it can lead to confusing results.

What if I really want to change the value of a block parameter based on the output of another block?

Since my last post on this topic, we introduced the Parameter Writer block. For a few releases, the Parameter Writer block was restricted to be used only in very specific contexts where the execution order was explicitly defined. In R2023a, we relaxed this constraint and the Parameter Writer block can be used in many contexts. Internally, we analyze the data dependency and make sure the blocks execution order reflects it.
To illustrate how the Parameter Writer block works, I decided to revisit another old blog post: You need an integrator with variable limits… there’s a solution for that!
In this post, I pointed out the fact that the Integrator block has an option to limit its output, but the limits can only be specified as dialog parameters:
At that time, the solution I found to limit the Integrator output using input signals was this complex contraption using the State and Reset ports of the Integrator:
As of MATLAB R2023a, if I am being asked to do the same, I would use two Parameter Writer blocks and bind them to the lower and upper saturation parameters of the Integrator block:
Here is an example model using the above subsystem, changing the integrator limits from +/-10 to +/-1 at t=50sec.

Use at your own risk!

I heard somewhere that With great power comes great responsibility and this applies here.
The following is an example I receive every once in a while, where the user wants to progressively change the frequency of a Sine Wave block, let's say from 3 rad/sec to 6 rad/sec over 5 seconds. As you can see, the frequency of the resulting sine wave does not smoothly increase from 3 rad/sec to 6 rad/sec. Instead, it looks twice faster than expected.
If the reason is not obvious to you, I recommend reading this MATLAB answer.
Exemplifying what I described above, the Sine Wave block makes the assumption that the frequency is constant. Based on this assumption, instead of integrating the time-varying frequency and computing the angle to be passed to sin:
y=sin(ω(t)dt)
The Sine Wave block assumes a constant value for ω and implements:
y=sin(ω*t)
Making ω increase linearly with time (ω(t)=k*t) and differentiating the result shows why the resulting function is twice the desired frequency:
ddt(k*t*t)=2*k*t
To get the desired frequency-increasing sine wave, you want to integrate the time-varying frequency:
Another tip here... if you implement this model, I recommend enabling the Wrap State option of the Integrator block. This will avoid its output to grow infinitely as the simulation time increases, which could lead to numerical issues for long simulations:
Because of these types of subtleties, I recommend using the Parameter Writer block only in contexts where it is executed only infrequently. This could be for example in a Triggered Subsystem, Function-Call Subsystem, Initialize Function, etc.

Now it's your turn

Are you a fan of the Parameter Writer block? Do you have challenges with this concept of "Signal vs Parameters" in Simulink? Let us know in the comments below.
]]>
https://blogs.mathworks.com/simulink/2023/09/27/signals-vs-parameters-in-simulink-and-the-parameter-writer-block/feed/ 6
What’s New in R2023b? https://blogs.mathworks.com/simulink/2023/09/15/whats-new-in-r2023b/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2023/09/15/whats-new-in-r2023b/#comments Fri, 15 Sep 2023 12:50:21 +0000 https://blogs.mathworks.com/simulink/?p=15146

With so many features and enhancements introduced each release, it's difficult to decide which ones to highlight on this blog. Here are a few of my favorites in R2023b.Variant NavigationIn R2023b, we... read more >>

]]>
With so many features and enhancements introduced each release, it's difficult to decide which ones to highlight on this blog. Here are a few of my favorites in R2023b.

Variant Navigation

In R2023b, we decided to make a few quality-of-life enhancements to variant subsystems. If you enable the content preview for a variant subsystem, we now display the content of the active variant instead of the variant layer. Also, when double-clicking on a variant subsystem, we now automatically jump right into the active variant. We hope this will save you a few clicks.
Here are the R2023a and R2023b behavior side by side:
VariantR2023b.gif

Timing Legend

Sample time colors and the Timing Legend have been completely revamped:
I like how you can now expand each sample time to see which blocks are introducing it:

Connectors

We added the possibility to display Connectors in the Simulink canvas to help finding blocks that are related, but don't have signal lines in between. This feature has been available for many releases for Simulink Functions and their corresponding Function Caller block, it has now been extended to State Writer/Reader and Data Store blocks. Here is a screenshot showing how it looks for Data Store blocks, along with the panel to toggle the different types of connectors:

Docked Type Editor

A few releases ago, we introduced a new Type Editor to replace the old Bus Editor. This release, we made it possible to dock the Type Editor in the Simulink canvas, allowing you to edit bus objects and other type definitions close to where they are being used.

Model Finder

After introducing the modelfinder function a few releases ago, we are now releasing a graphical interface for it. You can launch it by executing modelfinderui.
By default, the Model Finder allows you to find example models shipping with Simulink and all blocksets -- but it can do a lot more! It also allows you to create custom databases for you own models. You can filter your search and once you find a match, it displays the Model Description to provide you with additional information before opening the model.

Now it's your turn

Have a look at the Simulink release notes and let us know your favorite new addition, and also let us know if you see features you would like to be covered in more detail on this blog.
]]>
https://blogs.mathworks.com/simulink/2023/09/15/whats-new-in-r2023b/feed/ 3
Tips for Working with Simulink Libraries and Data Dictionaries https://blogs.mathworks.com/simulink/2023/08/08/tips-for-working-with-simulink-libraries-and-data-dictionaries/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2023/08/08/tips-for-working-with-simulink-libraries-and-data-dictionaries/#comments Tue, 08 Aug 2023 14:18:48 +0000 https://blogs.mathworks.com/simulink/?p=14927

I came across an interesting feature recently for Simulink® libraries that could be helpful when working with buses and other types associated with them. The Problem Let's say we have a library... read more >>

]]>
I came across an interesting feature recently for Simulink® libraries that could be helpful when working with buses and other types associated with them.

The Problem

Let's say we have a library with multiple blocks that use a specific bus on their interfaces, for example, myBus. When generating code for our models I recommend using non-virtual bus definitions so we can have strict control over how these buses appear in the code. This bus has 3 elements, a boolean, sel, and two uint32 values, a1 and a2. As a specific example, one of the blocks from our library uses this bus for a selection operation.
myLibBlock.png
When we want to use these library blocks in one of our models, we'll need to have myBus defined somewhere in the scope of this model. This means that each model that uses blocks from this library must have a setup script or be associated with a Simulink data dictionary. Conceptually, our setup would look like this diagram:
In the above figure, the yellow arrows indicate library block usage and the blue arrows show data dictionary links.

The Desired Situation

This setup works, but it would be better if we could have the definition of myBus come along with the library instead. This would save our library users time and streamline their workflows. Conceptually, we want to follow the guiding principle that the interface for a reusable component is stored with that component. With this in mind, our diagram should look like this:
Here the dictionary containing myBus will automatically be included in any model that uses blocks from the library. We'll show how to do this in the following section.

Associating a Dictionary with a Library

Let's start by creating the required bus definition in a data dictionary. From the Model Explorer, we choose File->New Data Dictionary and provide a file name. We'll call it myLibDict.sldd. Next, we'll select the Design Data section of the dictionary and choose Add->Simulink Bus, and rename the bus to myBus.
We'll add the elements to this bus using the new Type Editor interface:
typeEditor.png
In this interface, we can set up the element names, data type, etc. for our bus elements. Once we're done, we can see the bus definition in the dictionary in the Model Explorer:
myBusDef.png
Now that we have this definition, we associate myLibDict.sldd with myLib.slx. Start by selecting myLib in the left panel of Model Explorer and choosing the External Data tab in the right panel. In the Data Dictionary Field, enter myLibDict.sldd and press apply. Here I've cropped and zoomed in on the relevant panels.
AssocLibLeft.png AssocLibRight.png
Once we've done this, we can see this association in the External Data field in the Model Explorer:
myLibConf.png
Any model that uses the library will now automatically have access the bus definition. Specifically, myModel.slx, which uses the library block, can use the bus definition. In this case, the input is defined to be of type myBus. This is clear when we update the diagram for myModel.
myModel.png

Housekeeping for Library Dictionaries

Occasionally, we may need to restructure the files in a project or share it via archive. When we do this, the library dictionary dependencies will need to be recomputed because they are cached on disk in the user preferences file to increase performance during diagram updates. We'll show examples of how to handle these situations in this section.

Example 1: Reorganizing our Files

Now let's say we want to reorganize our project and move our library to a directory called "Libraries". Initially the files are all in the root folder of the project:
preMoveFolder.png
We create the directory "Libraries" and move myLib.slx and myLibDict.sldd to this directory and add it to our path:
postMoveFolder.png
After this move, we get an error when we try to simulate our model:
simError.png
To fix this error, we need to close the dictionary with Simulink.data.dictionary.closeAll() and refresh the links with Simulink.LibraryDictionary.refresh().
Simulink.data.dictionary.closeAll()
Simulink.LibraryDictionary.refresh('./Libraries')
This will update the cached dictionary dependency analysis and allow us to simulate myModel.

Example 2: Sharing an Archive

As a final example, let's say we want to share our project with a colleague via an archive, let's call it myProject.mlproj. We can prevent the above error when our colleague opens this project and attempts to simulate myModel by adding the following line to a project startup script. Here we can see the script myStartupScript.m in our project and the code in the editor. Note that the Run At Startup icon is set in the Status column (circled in red). We get this by right-clicking on myStartupScript.m in the project window and selecting Run At Startup from the menu.
StartupScript.png
This will allow our colleague to simulate and generate code from the model.

Now It's Your Turn

How do you store your buses and interfaces? Do you find this feature useful? Please let us know in the comments below.
]]>
https://blogs.mathworks.com/simulink/2023/08/08/tips-for-working-with-simulink-libraries-and-data-dictionaries/feed/ 6
Guy on Simulink Material on GitHub and MATLAB Online https://blogs.mathworks.com/simulink/2023/07/31/guy-on-simulink-material-on-github-and-matlab-online/?s_tid=feedtopost https://blogs.mathworks.com/simulink/2023/07/31/guy-on-simulink-material-on-github-and-matlab-online/#respond Mon, 31 Jul 2023 13:43:29 +0000 https://blogs.mathworks.com/simulink/?p=14879

Did you notice the recent blog post Open science and reusable research with MATLAB Online and GitHub by my colleague Mike Croucher on The MATLAB Blog?I decided to try adopting this new feature to... read more >>

]]>
I decided to try adopting this new feature to open GitHub repositories directly in MATLAB Online. That way, you will now be able to open my blog posts and related files in MATLAB Online in one click. As described by Mike, this will work even if you don't have a MATLAB license, all you need is a free MathWorks account.
Let's see how this works.

A GitHub repository for Guy on Simulink material

To make it easier for you to reproduce what I am covering on this blog, I created a GitHub repository: github.com/simulink/blog
For each post, I will add a folder in the repository with the MATLAB live script I used to create the post, along with all MATLAB scripts, functions, Simulink models, and other files I used while writing the post. In the above screenshot, you can see the folder for my previous post on debugging custom C/C++ code. More folders will be added as new posts gets published.
In case anyone is wondering, I use the Publishing tool for MATLAB® live script to WordPress to publish posts on this blog.

Opening Blog Posts in MATLAB Online

Did you notice the Open in MATLAB Online badge at the end of my last blog post?
If you click on the link the following will happen:
  • MATLAB Online will open and ask you to log in using your MathWorks account
  • The MATLAB live script will open in the MATLAB Editor, ready for you to read, execute, and modify.
This should make it easy for you to try and modify my examples directly in your web browser.
In case you would like to do the same with your GitHub repositories, the way to create the URL to open any GitHub repository in MATLAB Online is documented here: Open in MATLAB Online from GitHub.

A Simulink Example

It would be sad to end this post without at least opening and simulating a Simulink model. Here is a simple mass-spring-damper model:
mdl = 'ex_modeling_simple_system';
open_system(mdl);
Here is what the model looks like in MATLAB Online:
We can simulate it:
in = Simulink.SimulationInput(mdl);
out = sim(in);
and look at the results in the Simulation Data Inspector, which opens in a separate tab.
plot(out)

Now it's your turn

Start right now and open this blog post in MATLAB Online:
I hope you will like this new way to easily access all the files needed to reproduce my blog posts.
]]>
https://blogs.mathworks.com/simulink/2023/07/31/guy-on-simulink-material-on-github-and-matlab-online/feed/ 0