Guy and Seth on Simulink

How To Make Your Own Simulink Block 51

Posted by Seth Popinchalk,

Today I want to introduce a fundamental Simulink concept: masking a block.  Masking provides you with a way to put an interface on an algorithm.  This can centralize the system parameters for easier viewing, or hide the complexity from unintentional tampering by other users.  Masking can also be used to dress up your model for more inviting or professional looking presentations.  Let me show you how by masking a subsystem that I made.

The subsystem holds the algorithm

In my example, I am masking a subsystem that contains a fixed limit saturation algorithm:

Saturdation algorithm subsystem

I will come back to this in my examples below.

Improved Presentation: The Mask Icon

Simulink models provide an executable specification.  The model allows you to share a picture of the system schematics that can be understood by everyone on the team, especially your boss or customer.  The best way to do this is to make the components in your diagram really obvious.  A great example of this is the f14_digital demo model.  This model uses images for the icon on three root level subsystems.

f14_digital.mdl demo model

You can grab a picture of the stuff you are modeling and put it on the corresponding subsystems.  To do this, use the Edit > Mask Subsystem... menu when the block is selected.  This is also available from the right click menu on the block.  This opens the mask editor and brings up the icon tab for the block.

Mask editor GUI, Icon Tab

For my Saturation subsystem I have used the basic plot command to put an icon on the block.  I set the Units to normalized, which provide x and y range from zero to one for the canvas.

Saturation system with added icon

The allowed drawing commands are a subset of MATLAB graphics.  There are examples at the bottom of the mask editor.  The image command can be combined with IMREAD to load an image from your MATLAB path.  For example, the following drawing command adds a Boeing 747 icon to your block

image(imread('b747.jpg'))

Masked subsystem with a Boeing 747 image for the icon

Adding an icon to your system doesn’t change the behavior.  When you double click on the block, you will still open the system it contains.

Mask Dialog and Documentation

A mask can also provide a simplified interface to the blocks underneath.  As a trainer, I used to introduce this concept as a method for preventing unintended tampering with the contents of your system.  The parameters tab of the Mask Editor is where you set the parameters for the system.

Mask Editor: Parameters Tab

The Prompt is the string you want to display before the box where the user enters the value.  The Variable holds the value entered in the mask.  Adding dialog parameters creates a local workspace for the blocks under the mask.  In my fixed saturation example, the up and lo constant blocks will now use the variables from the mask as their value, instead of hard coding the constant in those blocks.

Saturation algorithm using variables to specify constant block values

Add some details to the documentation tab to complete the mask dialog.

Mask Editor: Documentation Tab

Mask type is used to specify a title for the dialog.  Mask description shows up right below that and provides a place for some quick reference documentation.  The Mask help field can be a long description that will be displayed as HTML when the user pushes the Help button.  HTTP links are also acceptable.  For a full list of the Mask help alternatives click here.  Double clicking on the icon of the Saturation block displays the finished dialog:

Finished Saturation dialog

As you make edits in the Mask Editor you will notice that your parameter values in this dialog are set to 0.  Before you finish with your mask, make sure to set the parameter values for your system in the dialog.

How do I get back to the system?

Now that the block has a mask, double clicking on the icon opens the mask dialog.  The way you know you are looking at a mask dialog is the label following the system name: Saturation (mask).  To see the algorithm beneath the mask, right click on the block and select Look Under Mask.  This will bring you back to the contents of the system.

Now it’s your turn

This is the tip of the masking iceberg.  Do you have masked blocks in your model?  What tricks have you used to polish up your model and make it look professional?  Tell me about it here.

51 CommentsOldest to Newest

I use the mask to display the values set in the mask parameters so the user can easily see what values have been set for the model. If unit-ed values (from units class) are used, the displays will show the appropriate units as well and convert the values back to doubles for use in the simulation. Text colors are changed to indicate different states of the parameter options or if an uninitialized condition exists in the model.

I also use functions to auto pad images so they display correctly on top of a subsystem as it is resized.

It is unfortunate (at least in 2007B) that the print to HTML web view do not capture the mask displays or give you an option to capture the mask displays.

Dear Seth,

I agree that masks are a very useful concept and I use masked blocks a lot. Together with the atomic subsystem property and hierachical resolution set to “none” you get the equivalent of a function for a Simulink block (clearly defined interface and execution order).

Just two questions / enhancement requests:

- Is there a shortcut for right click – look under mask? If you have a lot of masked subsystems it is really unconvenient allways to use the context menu.

- Please allow direct masking of Embedded Matlab function blocks, which is currently not possible. The behaviour could be as usual for masked subsystems:

left click – show mask dialog
look under mask – open Embedded Matlab editor

Today I have to wrap even a single Em function block with a subsystem to be able to use masks.

Best Regards

Georg Wiedermann

Hi,

Is it possible to display a picture on the subsystem (for. e.g image(imread(‘b747.jpg’)) ) and sitll have the port names visible. Currently the port names get hidden when the picture is displayed. I dont want to specifically name the ports as port_label(‘output’, 1, ‘xy’) etc. It should be dynamic.

Cheers,
Ryan

@Ryan – The current mask icon behavior doesn’t allow for using images and transparent masks. I have added your name to the list of people who have requested this.

As a workaround, if the number of ports on your block is not changing, you can use some Mask Initialization code to get the names and port numbers:

inputs=find_system(gcb,'LookUnderMasks','on','BlockType','Inport')
for i = 1:length(inputs)
s.(['port' num2str(i)]) = str2num(get_param(inputs{i},'Port'))
s.(['name' num2str(i)]) = get_param(inputs{i},'Name')
end

Then, in the mask icon drawing commands you can use the port labels.

image(imread('b747.jpg'))
port_label('input',s.port1,s.name1)
port_label('input',s.port2,s.name2)
port_label('input',s.port3,s.name3)

If there is a change to the name on a port, you will have to trigger the mask initialization code to refresh the names on the icon.

Hi

Is there a way to add an image to a mask and somehow link it permanently. I can successfully add an image to my mask, but as soon as I move out of the work directory, it cannot find the image if I want to use that subsystem.

I suggest using a command like this:

image(imread(‘C:\path\to\image\b747.jpg’))

The full path should be used in the IMREAD command to avoid the problem you are describing. If the image is on the MATLAB path, IMREAD will just find it. You can test this by running:

>> which b747.jpg

This file is on the path. Try that for your image, and then try adding the path to that folder.

Thanks Seth. Worked Like a charm :)

Is there no way, you can permanently link it though? Somehow embed the image into the mask.

Another option would be to add the image data to the block UserData. I always put the user data in a structure, in case I want to include multiple variables. At the command prompt:

s.im = imread(‘imagefile.jpg’);
set_param(blk,’UserData’,s)

Then, in the MaskInitialization

s = get_param(gcb,’UserData’)

And, in the mask code you should be able to call:

image(s.im)

Hi,

Is there a way to include a jpeg or even pdf image into the Mask Help box?
I tried it according to the Matlab help but it didn’t work out for me.
My goal is to write the entire help text including several pictures in another program and just save it as jpeg or pdf file.

I highly appreciate any help!
Thank you already in advance.

Seth,

Is there a way to access the value of an inport in a mask to either display it or be able to use it in logic in a callback?

Thanks,
Jay

@Jay and Wei,

You can look at an example I made where I use a level 2 s-function to dynamically set the color of a block based on the value of a signal:

http://www.mathworks.com/matlabcentral/fileexchange/23127

It uses a level 2 M-file S-function. Using get_param and set_param, you can configure a lot of things in a running model, including mask value.

To begin, I suggest using get_param and the “objectparameters” property to see all available properties of block or model. Once you found what you are looking for, tune it using get_param.

It would also be possible to do that using an event listener… let me know if you would like to know more about event listener, I think it is another cool feature.

Guy

Guy,

Thanks for the tip. Using your example I got this to work on my PC. My problem now is trying to get the s-function to compile to an xPC.

Thanks,
Jay

Hi seth,
I am a new user of Simulink. I want to use Switch for selecting two different parameters for different interval .for example i have 12 interval in which in “Odd interval” i want one parameter and in “Even interval” other parameter.But in switch block How to put this condition in “Threshold” which does not recognize U1 or U2 etc.Please suggest me.

Hello;

I am looking at the “sum” block in the simulink math library and have two questions regarding the mask.

1) How do I control the port placement on the mask icon? Using the circle sum feature I notice that the second port enters through the bottom. How is this done?

2) What is the appropreat “plot ()” instruction to draw a circle or an elipse?

Any help will be most welcome.

Regards

David

@Dave Lewis – The Sum block is a built-in block, and the parameters dialog is not created using the Mask Editor. You can not currently control port placement, but this is a popular requested masking feature.

As far as plotting a circle, I would use SIN and COS to create the data points and then use the plot command to display them on the block icon. There is a tech support solution that shows how this is done with a MATLAB figure here. You could put the following code in the initialization commands:

th = 0:pi/50:2*pi;
xunit = cos(th);
yunit = sin(th);

And the following in your icon drawing commands:

plot(xunit,yunit)

Make sure your Icon units is set to Autoscaled.

i am a new user of simulink. i want to know how to calculate auto spectral density of an audio data using ‘from wav file’ block

please tell me about add own model into library!
function blkstruct=slblocks
blkStruct.Browser(1).Library=’mylib1′;
blkStruct.Browser(1).Name=’Parentlib’;
blkStruct.Browser(1).IsFlat=1;

blkStruct.Browser(2).Library=’mylib2′;
blkStruct.Browser(2).Name=’Parentlib’;
blkStruct.Browser(2).IsFlat=1;
%here mylib1,mylib2 are subsystems with logical blocks
it’s only adding the last mylib2 in Parentlib…
please send me an email!

Hello there.

I am just a newbie with Simulink and I need some help. Could you please help me with a design of a simple “Flat top PWM ” circuit diagram. I have made of a SVPWM but I can’t really connect it to make a 120 degree, 60 degree or 30 degree.
I have read how to do it but whenever I connect I have an error message from my Plecs toolbox.

Many thanks

@Montasser, @nk, @Issopui – Your questions are a bit off topic for this post. Please try to get help from comp.soft-sys.matlab.

@uugan – I don’t know what is happening exactly. Please contact technical support with your simple example. The doc isn’t very descriptive about SLBLOCKS.m. I’ll add it to my list of topics for future posts.

hello sir …can u help me with a simulink diagram to generate pwm pulses for 7 level cascaded H bridge multilevel inverter using inverted sine wave as carrier(multi carrier technique)and sinusoidal reference signal .

sir …help me with a simulink diagram to generate pwm pulses for a 7 level cascaded ultilevel inverter with inverted sine wave as carrier (multicarrier type)and a sinusoidal reference signal

Sir,
i had generated both sine wave and triangular wave(through matlab coding),now the problem is i have to compare those and generate pulses to the inverter.can u tell how to generate pulses by comparing 2 waves,thanks in advance

Dear Seth,
I am trying to simulate factor-graphs in Simulink. They are probabilistic graphs that require bi-directional vector propagation.

SIMULINK would be great and I have started doing it, but when I enclose a group of functions into a subsystem, the fact the inputs and outputs show up always on opposite side makes the picture quickly a nightmare.

Is there a way, perhaps with a masking function, to change the position of inputs and outputs on the block appearance?

I know that this question must have arisen before, but it appears to me that it is an important limitation of Simulink for building hierachies of systems of growing complexity.

For example, it would be nice if we could group a set of blocks into a sybsystem and require the i/o layout to be preserved, and not switched around as it is now. I know it can be rotated or flipped, but it is not enough.

I would much appreciate to know if there is any effort at Mathworks on this issue.

I would be more than happy to share any factor-graph design toolbox with Mathworks.

@Vidhya subramanian and @murali krishna – Your comments are off topic for this blog post, and would be more appropriate on the MATLAB newsgroup. Good luck.

@Francesco – While I’m not familiar with factor-graphs, I have heard this request to provide bi-directional connections between systems. This is not possible using Masking, and does not work with standard Simulink signal lines. The Physical Modeling tools use special non-directional connections that might be more appropriate for representing the layout you describe, however, they may not provide the functionality you are looking for.

I have heard of people using the Connection Inport to create bi-directionally connected systems, however, I think this actually hides the data-flow aspects of Simulink. The Connection Inport is part of the Simscape product.

Dear Seth,
thanks for you very useful reply. I will look into Simscape to design my simulation model.
However, I still think that allowing inputs and outputs (standard one-directional Simulink) to be placed arbitrarily on a subsystem block may greatly enhance the capabilities of Simulink!!

Hello
can anyone help me modelling a photovoltaic panel using S-FUNCTION.
There are different types of s-function, i.e., when i search for s-function, the results give: Level 2 m-file, s-function and s-function builder…which one shall i use??
Iam new to matlab and any help will be hihgly appreciated.

Thanks
TK

Dear Seth,

My question is: How can I connect variables inside of Embedded Matlab Fcn Block in a subsystem with the mask parameter in the dialog box of this masked subsystem without a constant block wich is connected to Embedded Matlab Fcn Block???

Hi Guy,

I’m really sorry. Thank you very much for this hint. I thought Seth made a mistake with the Guy.

Hi,

I know that is no standard way in Simulink to work with strings. But I can’t believe that there is no mechanism implemented to use strings in Simulink and RTW. Can somebody give me an advise please how I can use strings in Simulink???

Regards

Andrej

Hi!
This was a good tutorial! Thanks!
I have one question.
After creating a mask, if I copy the block multiple times to create new blocks with different parameters and then I decide I want to change the mask slightly. How can I do that so that it affects all the blocks with that mask. Is there a way to ‘copy and paste’ block masks? Or can I save a single copy of a mask and apply it to multiple blocks at the same time?
Thanks
VivB

Hi,I am starter in simulink and matlab,
So how to bring the signal generated from Simulink to the matla, Which is basically generated by a RTW

Hi Guy,
I wanted to create a block in simulink a Parameter A whose value can be changed as per requirement. When try to edit a constant block available in sources which has value 1 to a alphabet say b i get error that it is an invalid choice. please help.

Hi,
I have created my own simulink blocks using masked subsystem.
The problem I am facing is simulation speed of the model. Whenever I update or simulate the model, it takes lot of time.

The mask initialization commands instantiates some primitive s-function blocks or some of my other subsystems, set their parameters and connects them.

How can I minimize simulation time?

@mandar – Any variable names you use as parameters must evaluate to variables in the MATLAB base workspace, the model workspace, or the mask workspace. Take a look at the post on hierarchical symbol resolution.

@Chandan – There can be many factors that affect the speed of simulation of the model. The mask code should only impact the initialization time. Try to isolate if the time is spent on initialization or simulation. To measure initialization try:

>> tic; set_param(bdroot,’SimulationCommand’,'Update’); toc

To measure the combined time of initialization and simulation, run:

>> tic; sim(bdroot); toc

Also, try reviewing the blog posts in the Performance Category.

i have some simple matlab code to describe the functionality of my project, and i wish to simulate my project through the simulink, how i do to create the block with only 1 input and 1 output?

Hi,
I want to have a mask subsystem which contains masked blocks.I should be able to set the properties of the masked block inside by setting the properties of parent subsytem.
Can you please help me on this.

I have a masked subsystem. Based on masked parameters I draw its internals. Before drawing, I want to validate mask parameters. If they are invalid, I want to give an error (maybe in the form of error dialog box).

I am doing this in mask callback. I am giving error for invalid parameter value using errordlg. Error dialog pops up when invalid value is entered. But that invalid value is retained by the mask. If I press Ctrl+D to update the model, invalid value is propagated inside the drawing of subsystem.

How can I give error to avoid above problem?

Hello, I have between 3 to 36 simpowersys “Connection ports” to add dynamically. Please help! I have blocks which are initialized by a callback from mask but I don’t know who to create only the needed amount of Connection Ports. Thanks

hi i want to ask about fuzzy block always appear error message (undefined function or variable)with any block i built it and in any system block in different subject

Hi there. Is it possible to have a rectangular subsystem (which is masked) to have ports on ALL four sides? How can we design that? Can the masked system be circular in shape? (like the round ADD block). Can we design polygons, with each side capable of taking input or giving output? Is it possible at least for electrical subsystems (where there is no direction)? Ex: a rectangular box with four electrical ports, one on each side. Thank you.

Add A Comment

What is 3 + 9?

Preview: hide

These postings are the author's and don't necessarily represent the opinions of MathWorks.