Guy on Simulink

Simulink & Model-Based Design

The variables you need

Today I want to share two lines of code I find very useful.

The problem

I often need to exchange models with users. One of the thing people struggle the most while doing that is providing the appropriate data needed by the model. Usually, I see two cases:

  • The user saves his entire MATLAB workspace in a MAT-file and sends that with the model. In such case, I often receive a very large MAT-file where only a few variables are actually needed.
  • The user tries to optimize and sends only the minimum set of variables, but forgets a few. This leads to an error like:

Undefined variable

The Solution

In an ideal world, my data would be generated by a script or stored in a data dictionary and all the dependencies would be taken care of by a Simulink Project.

However, for me it often happens that I need to share a model which is in a "debugging" state. For example, I have deleted half the blocks, modified data in the base workspace, etc. In that case, I want to store the data used by the model that is currently in the base workspace, without all the unnecessary variables.

In my opinion, the easiest way to make that happen is the following two lines of code:

Simulink.findVars

With Simulink.findVars, you get a list of all the variables in the base workspace used by the model, and with matlab.io.saveVariablesToScript, you generate a script that can recreate them.

File storing variables

Then if I want to be super-efficient, I will copy the content of that file to the model preLoad callback. That way I only need to send one file, and the data will be created automatically the next time the model is opened.

preload Callback

Now it's your turn

Give this technique a try next time you need to share a model; hopefully it will save you some time.

|

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.