MATLAB Function
MATLAB Function
Library
User-Defined Functions
Description
With a MATLAB Function block, you can write a MATLAB function for use in a Simulink model. The MATLAB function you create executes for simulation and generates code for a Simulink Coder target. If you are new to the Simulink and MATLAB products, see What Is a MATLAB Function Block? and Create Model That Uses MATLAB Function Block for an overview. Double-clicking the MATLAB Function block opens its editor, where you write the MATLAB function, as in this example:
To learn more about this editor, see MATLAB Function Block Editor. You specify input and output data to the MATLAB Function block in the function header as arguments and return values. The argument and return values of the preceding example function correspond to the inputs and outputs of the block in the model:
You can also define data, input triggers, and function call outputs using the Ports and Data Manager, which you access from the MATLAB Function Block Editor by selecting Edit Data. See Ports and Data Manager. The MATLAB Function block generates efficient embeddable code based on an analysis that determines the size, class, and complexity of each variable. This analysis imposes the following restrictions:
The first assignment to a variable defines its, size, class, and complexity. You cannot reassign variable properties after the initial assignment except when using variable-size data or reusing variables in the code for different purposes.
See Best Practices for Defining Variables for C/C++ Code Generation.
See Reassignment of Variable Properties. In addition to language restrictions, the MATLAB Function block supports a subset of the functions available in MATLAB. A list of supported functions is given in Functions Supported for Code Generation Alphabetical List. These functions include functions in common categories, such as: Arithmetic Operators like plus, minus, and power
Matrix operations like size, and length Advanced matrix operations like lu, inv, svd, and chol Trigonometric functions like sin, cos, sinh, and cosh
See Functions Supported for Code Generation Categorical List for a complete list of function categories. Note Although the code for this block attempts to produce exactly the same results as MATLAB, differences might occur due to rounding errors. These numerical differences, which might be a feweps initially, can magnify after repeated operations. Reliance on the behavior of nan is not recommended. Different C compilers can yield different results for the same computation. To support visualization of data, the MATLAB Function block supports calls to MATLAB functions for simulation only. See Call MATLAB Functions to understand some of the limitations of this capability, and how it integrates with code analysis for this block. If these function calls do not directly affect any of the Simulink inputs or outputs, the calls do not appear in Simulink Coder generated code. In the Ports and Data Manager, you can declare a block input to be a Simulink parameter instead of a port. The MATLAB Function block also supports inheritance of types and size for inputs, outputs, and parameters. You can also specify these properties explicitly. See Type Function Arguments, Size Function Arguments, and Add Parameter Arguments for descriptions of variables that you use in MATLAB Function blocks. Recursive calls are not allowed in MATLAB Function blocks.
Examples
The following models shows how to use the MATLAB Function block:
Using get_param
get_param is the primary MATLAB function for inspecting the existing properties of a model. Before using get_param the model must first be loaded into memory. This can be achieved by either opening the model manually (see Opening a New or Existing Model) or by using either of the the API functions load_system or open_system. This tutorial uses the simpleModel developed in the tutorial Simulink Essentials Building, Simulating and Visualizing Models, and assumes that it is has been opened. Assuming the name of a particular parameter of interest is known then get_param can be used to inspect the specific parameter of interest. Figure 1 give some examples of usingget_param. Note that some parameters do not effect the actual simulation (e.g. Name and Location) while other do (e.g. Solver and StopTime).
>> get_param('simpleModel','Name') ans = simpleModel >> get_param('simpleModel','Location') ans = 408 ans = ode45 >> get_param('simpleModel','StopTime') ans = 10.0 416 1032 616 >> get_param('simpleModel','Solver')
Figure 1: Examples of Using get_param to Inspect a Specific Parameter. There is also an optional input to get_param that will return a structure array containing a list all parameters and their current values. This is shown in Figure 2. Note that (as of R2010a of MATLAB) a Simulink model has 569 parameters, hence they are not all shown.
>> get_param('simpleModel','ObjectParameters') ans = Name: [1x1 struct] Tag: [1x1 struct] Description: [1x1 struct] Type: [1x1 struct] Parent: [1x1 struct] Handle: [1x1 struct] HiliteAncestors: [1x1 struct] RequirementInfo: [1x1 struct] SavedCharacterEncoding: [1x1 struct] Version: [1x1 struct]
Figure 2: Examples of Using get_param to Inspect All Parameters. Although not explicitly shown here, get_param is also used to inspect the parameters of blocks within a model. All blocks have a set of common parameters with each type of block having additional parameters that are specific to that block type.
Using set_param
The analogous function to get_param for modifying model and block parameters is calledset_param. It requires three inputs: the name of the object (block, model or signal) to modify; the property to modify; and the new value. Note that some properties are readonlyand hence cannot be modified. Some examples of using set_param are given in Figure 3.
>> set_param('simpleModel','StopTime','3'); >> set_param('simpleModel','Solver','ode23'); >> set_param('simpleModel','SimulationTime','10') ??? block_diagram parameter 'SimulationTime' is read-only.
reside. This may be required for instance if a particular block parameter is used to configure how a block behaves during simulation. Figure 4 gives an example of a MATLAB function that will automatically create a model. The code first checks to see if a model with the specified name already exists and if it does then it deletes it. A new model is then created using the API function new_system; the model is constructed using the API functions add_block and add_line; some model properties are modified (from their default values) using set_param; and finally the model is saved using save_system. All of the above occurs without the model becoming visible to the user.
function autoCreateModel % function to demonstrate how to create a simple Simulink model % Author: Phil Goddard ([email protected]) % Specify the name of the model to create fname = 'autoCreatedModel'; % Check if the file already exists and delete it if it does if exist(fname,'file') == 4 % If it does then check whether it's open if bdIsLoaded(fname) % If it is then close it (without saving!) close_system(fname,0) end % delete the file delete([fname,'.mdl']); end % Create the system new_system(fname); % Add a Sine Wave, making the sample time continuous add_block('built-in/Sin', [gcs,'/Sine Wave'],... 'Position', [140 95 170 125],... 'SampleTime','0'); % Add a gain block, setting the gain value to 2 add_block('built-in/Gain', [gcs,'/Gain'],... 'Position',[240 95 270 125],... 'Gain','2'); % Add a scope block
add_block('built-in/Scope', [gcs,'/Scope'],... 'Position',[350 94 380 126]); % Connect the sine and the gain add_line(gcs,'Sine Wave/1','Gain/1') % Connect the gain and the scope add_line(gcs,'Gain/1','Scope/1') % Set a couple of model parameters to eliminate warning messages set_param(gcs,... 'Solver','FixedStepDiscrete',... 'FixedStep','0.1'); % Save the model save_system(fname);
Figure 4: Different Syntaxes for the sim Function. Executing the code given in Figure 4 creates a model called autoCreatedModel. It is shown in Figure 5 along with the output when the model is simulated.
This tutorial has discussed topics related to using the MATLAB-Simulink API. Other Simulink tutorials are available on the Software Tutorials page.
Contents
Start With a New System Adding Blocks and Lines Deleting Blocks and Lines Replacing Blocks Now it's your turn
x = 30; y = 30; w = 30; h = 30; offset = 60; I like my ports with slightly different proportions, so I define them to be half the height of the other blocks.add_block specifies the source block and the destination path, which defines the block name. Block names must be unique for a given system so add_block provides a MakeNameUnique option. (not used here) pos = [x y+h/4 x+w y+h*.75]; add_block('built-in/Inport',[sys '/In1'],'Position',pos); I'll add an integrator block, offset to the right of the inport.
add_block('built-in/Integrator',[sys '/Int1'],'Position',pos) To connect the blocks, call add_line and provide the system name, source port and destination port. The ports are designated by the 'blockname/PortNum' format. Default line routing is a direct line connection from the source to destination. I prefer to use the autorouting option.
add_line(sys,'In1/1','Int1/1','autorouting','on')
When adding multiple blocks and lines, I group them into add_block/add_line pairs to keep myself organized.
pos = [(x+offset*2) y (x+offset*2)+w y+h]; add_block('built-in/Integrator',[sys '/Int2'],'Position',pos) add_line(sys,'Int1/1','Int2/1','autorouting','on') pos = [(x+offset*2) y+offset (x+offset*2)+w (y+offset)+h]; add_block('built-in/Scope',[sys '/Scope1'],'Position',pos) add_line(sys,'Int1/1','Scope1/1','autorouting','on')
Replacing Blocks
Sometimes you don't really want to delete a block, you are just going to replace it. replace_block gives you the capability to replace all blocks that match a specific criteria. I reccommend carefully reading the documentation to better understand this function. replace_block(sys,'Name','In1','built-in/Sin','noprompt'); set_param([sys '/In1'],'Position',[x y x+w y+h],'Name','Sine Wave');
By Seth Popinchalk
05:20 UTC | Posted in Commands, Fundamentals | Permalink | 63 Comments You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response. Pinging is currently not allowed.
63 Responses to Building Models with MATLAB Code 1. Bob replied on January 21st, 2010 at 17:25 UTC :
Yes, Ive used the model construction commands. Occasionally to build up models. More interestingly to use MATLAB and library blocks with the option turned on to modify contents to populate the block based on mask parameters. Amazing what one can do that way, Ive been able to avoid writing S-Functions with the approach. Ive occasionally needed to replace blocks, but never quite had replace_block work. Problems having lines reconnect with more than one inport/outport. Problems because dialog parameters need to be transformed for the new block.
2.
I have done this extensively. Ive also used commands to create/populate Stateflow flowcharts. One great use Ive found is to automatically connect multiple component models into a complete system model. Once the script works, for large models this approach is much faster and much more accurate than connecting ports by hand.
3.
@Bob I like you example of using self modifying blocks in place of S-functions. I find REPLACE_BLOCK is a really powerful tool for updating models that might use an obsolete utility block. @Jim I have never written code to connect up large system models into components, but I have seen the results. This is when auto line routing can really improves the look of the diagram. Thanks for your comments!
4.
Seth, thank you very much! I have additional question. Is it possible to alter Simulink model built into executable? I need a way for changing Simulink model on machine where I have only Matlab Runtime Environment.
5.
@Aleksandar If you build a Simulink model into an executable using Real-Time Workshop, you will only be able to modify the run-time parameters of the model. Using the Rapid Simulation Target (RSIM), you can useRSIMGETRTP to get a run-time parameter structure. This can be modified in MATLAB, saved to a MAT-file and passed into your executable as an argument. Look at the Accelerated Simulations Demos in Real-Time Workshop for examples of how to do this. If your goal is to modify the MDL file and use the SIM command to run it, that will not work in a deployed MATLAB application.
6.
Hi, Seth! Thank you for your advices! I have one question, but I am not sure is this right address for it. Anyway, Ive been working in SimPowerSystems for a short period of time. I would like to know is there any possibility of speeding up a simulation, since any model I have run seems to work in a real time. To be more specific, I would like to model how much energy (power KWh) would wind turbine produce in a year, using some of prefabricated models inside SimPowerSys. So, if I put that time (365*24*3600) in the simulation, it seems it would work for a month. Thank you very much, I would appreciate your answer very much!
7.
@Marko Simulink include Accelerator and Rapid Accelerator modes which can help speeding up models. However in your case I am not sure this is the appropriate option. You probably noticed that SimPowerSystems include Wind Farm demos implemented in two ways: detailled and average. For most applications, I recommend having a detailled model to study the transitional dynamics of the system over a short period of time. For the long term you want an average model which will skip details but will run fast.
8.
@Guy Thank you for you effort, but as far as accelerators are concerned ,they compile model into c code and than use some techniques to accelerate the model, but in my application that is not very suitable. Regarding those average models, you will notice that both detailed and average are run for 0.2 sec in approximately same speed (I have put for ex. 100 sec for simulation time, it seems to run forever). However, I was wondering if there is any model that could be run for much longer time. Thank you anyway!
9.
I am trying to deploy a model on a web. To do so, first I have to build a model using RTW, but when I try to build it, it shows me following message: Algebraic loops are not supported in generated code. Use the ashow command in the Simulink Debugger to see the algebraic loops. I started with very simple model, which has a loop. I desperately need to work this through. Is there any alternative solution for this? I would be very grateful for any answer! Thank you!
Ive a question regarding the add_line, delete_line etc. I have to always use power Sim, but I cannot use delete_line for deleting lines between some models.For example, I cannot delete lines connecting two distributed parameters line models, or I can delete or add line to/from the most of ports of Three-phase V-I measurement model. Ive tried all the below commands: delete_line('Ps_circuit','Section 2/1','Section 3/1') delete_line('Ps_circuit','Section 2/1','Section 3/1') delete_line('Ps_circuit','Three-Phase V-I Measurement1/3','Section 1/1') Whilst the command works for some ports such as Three-Phase V-I Measurement1/1 ! Actually, it returns error messages such as Invalid Simulink object name: Three-Phase V-I Measurement1/3. Could you please give some idea what the problem is? Regards,
Seth, way back in the good old days of R13 there was the save_as(..., 'm') command. Given a model, it could write an m-script, that when executed, let the model reappear by magic (nowadays this works for figures only). In this spirit, Id like to know, whether there is something like a macro recorder in Simulink: Switch it on, tell it where to store the result and start to draw your model. I expect it to record all my gestures and moves with the mouse and the keyboard as model construction commands and after stopping the recording, we get that model-constructing m-file. No typing, no calculation. Edit the resulting m-file to polish it according to your needs. Is there such a feature in Simulink? I could not find it.
BTW, in response of your question: The cosine comes out of the integrator, which has initial condition zero, which explains why the signal does not cross zero. Cheers, Emile
Gentlemen, I have learned a lot since I inquired further about the keystroke recording in Simulink. I thought it would be useful for an application where I need to first have a bunch of display scopes present, and then remove them. I thought this repetitive operation could be learned in a macro so I didnt have to write the script. But then I got to wondering about a different method of removing lines, and now I have colored all the lines to be removed every time as green, and learned how to select and delete all the green lines and blocks with about four lines of script. But one thing I could still use advice on is where to find a complete list of line properties, because I could really extend the utility of this script by knowing more about the line properties.
Leave a Reply
Click the "Preview" button to preview your comment here. Name (required) E-mail (required, will not be published) Website (optional) Spam protection (required): What is 2 + 3 ? Wrap code fragments inside <pre> tags, like this: <pre class="code"> a = magic(3); sum(a) </pre> If you have a "<" character in your code, either follow it with a space or replace it with "<" (including the semicolon).