MATLAB Function

30
MATLAB Function Include MATLAB code in models that generate embeddable C code 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 :

Transcript of MATLAB Function

Page 1: MATLAB Function

MATLAB Function

Include MATLAB code in models that generate embeddable C code

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:

Page 2: MATLAB Function

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.

See Best Practices for Defining Variables for C/C++ Code Generation.

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 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.

Data Type Support

The MATLAB Function block accepts inputs of any type that Simulink supports, including fixed-

point and enumerated types. For more information, see Data Types Supported by Simulink.

For more information on fixed-point support for this block, refer to Fixed-Point Data Types with

MATLAB Function Block.

The MATLAB Function block supports Simulink frames. For more information, see Sample- and

Frame-Based Concepts.

Page 3: MATLAB Function

Parameters and Dialog Box

The block dialog box for a MATLAB Function block is identical to the dialog box for a Subsystem

block. See the reference page for the Subsystem, Atomic Subsystem, Nonvirtual Subsystem,

CodeReuse Subsystem blocks for information about each block parameter.

Examples

The following models shows how to use the MATLAB Function block:

sldemo_radar_eml sldemo_eml_galaxy

Characteristics

Direct Feedthrough Yes

Sample Time Specified in the Sample time parameter

Scalar Expansion Yes

Dimensionalized Yes

Multidimensionalized Yes

Zero-Crossing Detection No

Building Simulink Models using MATLAB Code

MATLAB has an extensive API (Application Program Interface) for building and modifying

Simulink models from MATLAB code. This may be from either the MATLAB command

line, from within a function or script, or from anywhere that m-code can be executed.

This tutorial discusses several of the more common functions used to build and/or

manipulate a Simulink model using m-code. The primary functions for this

are get_paramand set_param. They enable every property of a model or block to be

inspected and changed respectively from MATLAB code. Note that there are many

hundreds of parameters, and for most the default settings are sufficient.

The topics covered in this tutorial are,

Page 4: MATLAB Function

1. Using   get_param .

2. Using   set_param .

3. Building a Model Using M-Code .

Other tutorials discussing Simulink and its applications for model based design are

available on the Software Tutorials page.

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 416 1032 616

>> get_param('simpleModel','Solver')

ans =

ode45

>> get_param('simpleModel','StopTime')

ans =

10.0

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.

Page 5: MATLAB Function

>> 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 read-

onlyand 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.

Figure 3: Examples of Using set_param.

Building a Model Using M-Code

It is possible to build a Simulink model using purely MATLAB code -- without using the

usual visual, point and click, mouse operations. Although rarely done, it does show how

to use various of the MATLAB-Simulink API functions.

The API functions are particularly useful for developing custom blocks with functionality

that include the ability to automatically modify themselves or the model in which they

reside. This may be required for instance if a particular block parameter is used to

configure how a block behaves during simulation.

Page 6: MATLAB Function

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]);

Page 7: MATLAB Function

% 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.

Figure 5: The Automatically Created Model.

This tutorial has discussed topics related to using the MATLAB-Simulink API. Other

Simulink tutorials are available on the Software Tutorials page.

Page 8: MATLAB Function

Guy and Seth on Simulink

January 21st, 2010

Building Models with MATLAB Code

Occasionally I get questions about how to build, modify, and add blocks, to Simulink models using

MATLAB commands. In this post, I will to give a basic overview of the common model construction

commands.

Contents Start With a New System

Adding Blocks and Lines

Deleting Blocks and Lines

Replacing Blocks

Now it's your turn

Start With a New SystemBecause you need to refer to the system so often when doing model construction from M-code, I

immediately save that off in a variable called sys. The new_system command created the empty

model in memory, and you have to call open_system to display it on-screen.

sys = 'testModel';new_system(sys) % Create the modelopen_system(sys) % Open the model

Page 9: MATLAB Function

Adding Blocks and LinesWhen I add blocks to the canvas, I specify the position to provide proper layout. The position

parameter provides the top left (x,y) and lower right (x+w,y+h) corners of the block. The x and y

values are relative to the origin (0,0) in the upper left corner of the canvas; x increases to the right,

and y increases down. To keep my layout organized, I use a standard blocks size of 30 by 30, and

offsets of 60.

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.

pos = [(x+offset) y (x+offset)+w y+h];

Page 10: MATLAB Function

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')

Page 11: MATLAB Function

Deleting Blocks and LinesWhen deleting blocks, I call delete_line before delete_block. This is the reverse of what I

did before. The commands are grouped in delete_line/delete_block pairs. For this

example, I'll delete the integratorInt2, and add an outport.

delete_line(sys,'Int1/1','Int2/1')delete_block([sys '/Int2'])

pos = [(x+offset*2) y+h/4 (x+offset*2)+w y+h*.75];add_block('built-in/Outport',[sys '/Out1'],'Position',pos)add_line(sys,'Int1/1','Out1/1')

Page 12: MATLAB Function

Replacing BlocksSometimes 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');

Page 13: MATLAB Function

[t,x,y] = sim(sys);plot(t,y), ylim([-.5 2.5]), grid on

Now it's your turnDo you use model construction commands? Why doesn't the cosine on that scope cross below

zero? Leave acomment here with your thoughts.

Get the MATLAB code  

Published with MATLAB® 7.9

By Seth Popinchalk

Page 14: MATLAB Function

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, I’ve 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, I’ve been able to avoid writing S-Functions with the approach.

I’ve 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. Jim replied on January 21st, 2010 at 17:39 UTC : 

I have done this extensively. I’ve also used commands to create/populate Stateflow

flowcharts.

One great use I’ve 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. Seth replied on January 21st, 2010 at 19:52 UTC : 

@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. Aleksandar  replied on February 3rd, 2010 at 11:40 UTC : 

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. Seth replied on February 3rd, 2010 at 21:42 UTC : 

Page 15: MATLAB Function

@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. Marko replied on February 10th, 2010 at 07:56 UTC : 

Hi, Seth! Thank you for your advices!

I have one question, but I am not sure is this right address for it. Anyway, I’ve 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. Guy  replied on February 10th, 2010 at 13:28 UTC : 

@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. Marko replied on February 12th, 2010 at 08:04 UTC : 

@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. Marko replied on February 26th, 2010 at 10:29 UTC : 

Thank you all for comments!

Page 16: MATLAB Function

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!

10. Seth replied on February 26th, 2010 at 13:24 UTC : 

@Marko – Real-Time Workshop doesn’t generate code for models that contain algebraic

loops. The only option is to remove them from your model. There is a technical support

solution entitled: What are algebraic loops in Simulink and how do I solve them?

I recommend you review that information and see if you can resolve the algebraic loop. Good

luck!

11. Mark replied on March 4th, 2010 at 03:55 UTC : 

Seth, thank you very much for this post!

I have additional question. Is it possible to rotate/flip blocks with model construction

commands? Thank you!

12. Guy  replied on March 4th, 2010 at 13:21 UTC : 

@Mark, Rotate anf flip can be done using set_param(gcb,’orientation’,'right’) where you can

replace ‘right’ by ‘left’, ‘up’,'down’.

The list of all the common block parameters that can be configured using SET_PARAM can be

found here:

http://www.mathworks.com/access/helpdesk/help/toolbox/simulink/slref/f23-7517.html

13. Mark replied on March 4th, 2010 at 21:44 UTC : 

@Guy, thank you for the promt reply and link.

14. Marko replied on March 8th, 2010 at 11:33 UTC : 

@Seth, I want to thank you on your valuable comment and I would appreciate if you could tell

me if Real-Time Workshop is going to support that functionality (“generate code for models

that contain algebraic loops”) in future releases.

Thank you very much again!

15. Jesus replied on March 9th, 2010 at 03:26 UTC : 

Thanks for your post on Simulink model construction commands, but where could we obtain

the commands for Simscape models. I infer it uses the same commands, but how can they be

Page 17: MATLAB Function

parametrized? Could you give us some examples?

Thanks

16. Guy  replied on March 9th, 2010 at 13:39 UTC : 

@Jesus – Construction commands are not fully supported for Simscape blocks. For example

ADD_BLOCK works fine, but the way to use ADD_LINE is not documented and consequently

not supported.

It is possible to use set_param and get_param on Simscape blocks, however the following

documentation page warns you:

http://www.mathworks.com/access/helpdesk/help/toolbox/physmod/simscape/ug/bqqjdvg-

1.html

It mentions that “You can use the Simulink set_param and get_param commands to set or get

Simscape block parameters. The MathWorks does not recommend that you use these

commands for this purpose.”

Based on experience, I use set_param with Simscape blocks only to set the value of some

dialog parameters, for example to set the resistance of a Resistor block you can do

“set_param(gcb,’R',’100′)”.

17. Seth replied on March 18th, 2010 at 20:48 UTC : 

@Marko – As you know, algebraic loop solving is an iterative process and doesn’t guarantee a

solution. It is also not appropriate within an embedded system without some kind of control for

performance.

I have heard other requests for support to generate code from models that contain algebraic

loops, but these are generally in the context of rapid simulation/batch simulation.

I wonder if your situation is the same? I have passed this on to our developers to consider for

a future release. Thanks!

18. Alex replied on March 22nd, 2010 at 16:45 UTC : 

Seth – I would like your advice on using systems for rapid prototype development.

19. rajshekhar replied on April 8th, 2010 at 16:29 UTC : 

i have a question that can m-file code dump into input port in simulink model?

20. Hadi Ariakia replied on April 17th, 2010 at 13:01 UTC : 

Hi Seth

Thanks a lot, it is really useful.

Page 18: MATLAB Function

I’ve 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.

I’ve 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,

21. Guy replied on April 19th, 2010 at 13:32 UTC : 

Hi Hadi,

Please see my post above. Construction commands like add_line and delete_line are not

documented and consequently not supported for physical signals, including

SimPowerSystems.

For these blocks, you will be able to use add_line for simulink ports, but not for physical ports.

Guy

22. Guy replied on April 19th, 2010 at 13:40 UTC : 

Hi Hadi,

I apologize for my previous post. You can find information on how to connect

SimPowerSystems blocks here:

http://www.mathworks.com/access/helpdesk/help/toolbox/physmod/powersys/ug/f1-

32601.html

Guy

23. Hadi replied on April 25th, 2010 at 14:32 UTC : 

Hi Guy

Thank you very much indeed.

Page 19: MATLAB Function

24. raju replied on May 16th, 2010 at 15:02 UTC : 

hi

thank you seth and others discussed here.

can you help me in reading the propagated signal names of the vector muxed with n lines one

by one through a code.

25. raju replied on May 16th, 2010 at 15:06 UTC : 

hi

can i assign signal names of the lines composed in a vector by naming the vector directly.

wil be looking for answers eagerly.

please help

26. tong  replied on May 25th, 2010 at 05:36 UTC : 

Hello!

I have just installed the MATLAB2010.But in the simulink part,the block of Embedded

MATLAB fuction can not be used.

It always said’the block can’t be found’.However, the other blocks of User-Defined Fuctions

can be used.

So please give me a hand.Thank you!

27. Rajshekar replied on June 4th, 2010 at 02:41 UTC : 

HI,

is there a command helpful to add a branch line from a signal in simulink.

i.e, one signal to many blocks.

28. Guy  replied on June 4th, 2010 at 12:53 UTC : 

Rajshekar,

ADD_LINE can be used for that. For example:

add_line(gcs,’Constant/1′,’Display1/1′)

add_line(gcs,’Constant/1′,’Display2/1′)

will first connect “Constant” with “Display1″. The second line will branch out from the line just

created and finally “Constant” will be connected to both “Display1″ and “Display2″.

Guy

29. Jörg replied on August 15th, 2010 at 14:19 UTC : 

Page 20: MATLAB Function

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, I’d 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.

30. pydiraju replied on September 1st, 2010 at 06:18 UTC : 

Hi seth,

thank you verymuch for your nice tutorial

pydiraju

31. Thomas replied on October 1st, 2010 at 16:10 UTC : 

Tong,

In 2007b, it is possible. Reminder, Matlab is Case Sensitive

I tried :

add_block(‘simulink/User-Defined Functions/Embedded MATLAB

Function’,'untitled/Embedded’)

and it works.

It’s a bit more complex to fill though.

32. Emile replied on October 14th, 2010 at 09:22 UTC : 

Hi Seth,

Thanks a million for this great tutorial. This is exactly what I needed. First I tried doing this with

the

get_param

and

set_param

commands, but this is WAY easier. Fixed in a minute, what I was trying to do for the last half

an hour!

Page 21: MATLAB Function

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

33. Seth replied on October 14th, 2010 at 12:28 UTC : 

@Emile – I’m glad it worked! I’m also glad to see you noticed why the Cosine doesn’t cross

zero! You are the first to respond to that question. THANKS!

34. Sneha replied on November 16th, 2010 at 21:42 UTC : 

Hello,

My name is Sneha.

I have following question.

I have two subsystems at the top most level in model and the first subsystem has 2 output

ports and the second one has two input ports.

I want to join outputs of first to inputs of second by add_line. But I am getting an error ‘???

Error using ==> add_line. Invalid Simulink object specifier.’ for the second command in the

following commands

I tried to add line as follows:

add_line(Name_model,’Filter/1′,’Output/1′)

add_line(Name_model,’Filter/2′,’Output/2′)

Is this approch correct?

Can you suggest me a solution?

35. Zohaib replied on December 10th, 2010 at 21:31 UTC : 

Hi everyone,

Is there a way to connect two ports based on their port names rather than numbers?

For instance I have in System A I have a port named A_port and in System B I have a port

named B_port. I want to connect them based on their names, NOT the port numbers.

Thanks,

-Z

36. vahid replied on December 25th, 2010 at 16:01 UTC : 

Hello Seth,

I’m a master student of electrical engineering. I want to work at controlling of wind turbines

with matlab/simulink.

I wiil be so thanlful if you help me at this major.

Best regards

vahid

Page 22: MATLAB Function

37. Joe Heinrichs replied on July 15th, 2011 at 12:04 UTC : 

Thanks Seth, this is great and it just saved me a ton of time and effort.

38. Seth Popinchalk replied on July 15th, 2011 at 13:27 UTC : 

@Sneha – I’m not sure why it isn’t working. Make sure the block names are exactly the same.

You can select the block, then type

gcb

to see what the block name is.

@Zohaib – Connecting by name is not available in the ADD_LINE function, but it is pretty easy

to accomplish with a few lines of code. Get the port names of the subsystems, and the port

numbers, then search for matches. When a match is found, connect those ports.

@Joe Heinrichs – I am glad you found this post!

39. M Hakkeem replied on July 26th, 2011 at 12:37 UTC : 

Hi,

I want construct stateflow(inside chart: state, transition, Junction like…….) model from m

script.

is it possible?

40. Guy Rouleau replied on July 26th, 2011 at 13:34 UTC : 

@M Hakkeem.

Yes it is possible. This section of the documentation will teach you how:

http://www.mathworks.com/help/releases/R2011a/toolbox/stateflow/api/f13-6010.html

41. M Hakkeem replied on July 27th, 2011 at 06:27 UTC : 

Thanks(Nantree in Tamil Language) Guy Rouleau.

42. M Hakkeem replied on July 27th, 2011 at 09:01 UTC : 

Hi

I want to track my transition action from default transition to end active transition while running

the model.

Can we do this? and How Can do?………

43. M Hakkeem replied on July 29th, 2011 at 03:03 UTC : 

Hi

Page 23: MATLAB Function

I am expecting your reply………I thing you are too busy….

Thanks

44. M Hakkeem replied on August 11th, 2011 at 04:08 UTC : 

I want to track my transition action from default transition to end active transition while running

the model.

45. chandan replied on September 28th, 2011 at 05:49 UTC : 

Good tutorial!

I am constructing a big model from matlab code.

It involves around 2000 blocks. I need to set position of these blocks.

What is the limitation on ‘Position’ parameter? I want to know what are boundary values for

positioning blocks.

46. Seth Popinchalk replied on September 28th, 2011 at 22:54 UTC : 

@Chandan – The limit for a Model window coordinate is 32768, BUT I strongly reccomend

keeping them within the limits of your screen. Subsystems and model reference hierachy

make models much easier to work with. Every time I have seen a Simulink model that looks

like an Eye-exam-chart, there have been problems lurking… often simple things like

unconnected lines, or extra blocks. Those kind of errors can drive you nuts and models that

your can’t easily browse will drive you insane when debugging. There is a documentation

page dedicated to Simulink Limits here.

47. chandan replied on September 29th, 2011 at 05:07 UTC : 

Taking your suggestion, I will design my model using subsytem in hierarchial manner.

Thanks for prompt reply.

48. Dhiraj replied on November 9th, 2011 at 11:20 UTC : 

Hi,

It was great to go thru the post and the discussions.

I was trying to generate the subsystem of the model I have constructed and make it an s-

function for my next model. I just couldnot make it, If anyone have tried and or done, would be

of great help to be informed.

49. Dhiraj replied on November 9th, 2011 at 11:26 UTC : 

I am trying to generate it using the model construction commands…

50. Snehal replied on December 29th, 2011 at 06:53 UTC : 

how to ‘fitSystem to Display’ in simulink dynamically.it is option available in View Menu of

Simulink Model.

Page 24: MATLAB Function

51. Seth replied on February 8th, 2012 at 10:16 UTC : 

@Snehal – I use the Space Bar to fit the system to view.

52. Wintersprite replied on February 9th, 2012 at 10:32 UTC : 

Gentlemen, your posts are great and touch on odd topics that are not explained so well in the

documentation. You never answered the guy last year who wondered whether there was any

possibility of a “model construction recording mode,” like recording a macro in Excel. You

would record everything as you built the model, and then it could generate the corresponding

m-script from it. What are the prospects for this?

53. Guy Rouleau replied on February 9th, 2012 at 13:53 UTC : 

@Wintersprite: This is a good point. Currently, MathWorks does not provide such feature.

However, you are not the first person asking for that. Our development team is aware of this

and considering it.

Can you let us know a bit more details on your use case? Why this feature would be useful for

you?

54. Sriharsha replied on February 11th, 2012 at 04:14 UTC : 

Hi,

i have an application where i need to create a subsystem using a GUI.

I have a model with a gain block and a filter block , followed by a scope, where my input is a

sine wave.

Now i need to create a subsystem , in which i should include the gain and filter blocks into it

(subsystem).

I need to do this using GUI.

The implementation flow is like:

I should select blocks and then i need to click a button on GUI, and then a subsystem should

be created in place of blocks.

Can any one please help me in doing this??

Regards

Sriharsha S

55. Wintersprite replied on February 17th, 2012 at 10:36 UTC : 

Page 25: MATLAB Function

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 didn’t 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.

56. Sobhi replied on April 10th, 2012 at 12:18 UTC : 

Hello,

Is there a way you can replace a subsystem from one model with a subsystem from a differnet

model keeping all the connections after you replace it? I am trying to do this in M script.

Regards,

Sobhi

57. Seth  replied on April 10th, 2012 at 12:23 UTC : 

@Sobhi – I think the function you are looking for is replace_block. Try using the full path to the

subsystem (‘model/Block_name’) for your new_blk value.

58. K replied on April 20th, 2012 at 02:48 UTC : 

In continuation to @Hadi(20)/Guy(22),

I’ve managed to connect physical ports using the add_line documnetation Guy provided. It’s

when I try to delete lines connecting physical ports that I get errors.

I’ve tryied the following command:

>>> delete_line(sys,hblk(2,i).RConn,hblk(4,i).RConn);

and got the following error

??? Invalid line specifier.

1. Is it possible to delete lines connecting physical ports using the delete_line() function?

2. If so, how exactly?

K

59. K replied on April 20th, 2012 at 15:49 UTC : 

@K – The solution I came up with is

delete_line(find_system(sys,’findall’,'on’,'type’,'line’,'SrcBlockHandle’,sbh))

Page 26: MATLAB Function

where sbh is the SrcBlockHandle in the source block.

60. Merle replied on May 4th, 2012 at 06:42 UTC : 

Is there a way to rotate a block with a command out of the command window, so the model

looks more well-arranged?

61. Patrick replied on August 16th, 2012 at 10:07 UTC : 

@Merie I use the block parameters blockRotation, orientation, and position to make my

models look clean. If you use the get_param function on a block that you have set up by hand

you can find out the exact settings for that block and add them to your add_block code.

Example:

% Start by adding a desired block to an empty system and stretching, positioning and rotating

until content. Then use these three lines below to find out the parameters.

blk_rot = get_param([path '/blkName'],’BlockRotation’)

blk_O = get_param([path '/blkName'],’Orientation’)

blk_pos = get_param([path '/blkName'],’Position’)

% Now that you have those parameters either hard code them into your add_block code or

make them variables in your code for easy changes. one other option if you want to just

change an existing blocks looks you can simply use set_param function.

add_block(‘blk_library’,[path '/blkName'],…

‘MakeNameUnique’,'on’,'position’,pos,’BlockRotation’,180,…

‘Orientation’,'Right’);

% or

set_param([path '/blkName'],’BlockRotation’,'blk_rot’);

set_param([path '/blkName'],’Orientation’,'blk_O’);

set_param([path '/blkName'],’Position’,'blk_pos’);

Hope this helps!

-Patrick

62. samy replied on October 22nd, 2012 at 16:15 UTC : 

Hello,

I am having a problem with the 3 phase V-I measurement connected to one terminal of the

generator and its other terminal rectified then connected to a D.C load(also the same problem

when the generator is unloaded).

the error is (Input two of Voltage Measurement block ‘SEIG/Three-Phase V-I

Measurement/Model/VI/Va’ is not properly connected to the network.)

Page 27: MATLAB Function

63. Quang replied on October 25th, 2012 at 04:16 UTC : 

Hello guys,

Let’s say I have two blocks A and B that are connected by a signal. I would like to copy A, B

AND the signal to some subsystem in the SAME model using Matlab APIs. Any ideas?

Leave a ReplyClick 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 "&lt;"

(including the semicolon).