Simulink-a Brief Introduction

Introduction

1. It is an interactive, graphics-based program that allows you to solve problems by creating models using a set of built-in “blocks.”
2. It is part of the MATLAB software suite, and requires MATLAB to run.

Applications

1. Designed to provide a convenient method for analyzing dynamic systems, i.e., systems that change with time.
2. It found early acceptance in the signal processing community, and is reminiscent of the approach used to program analog computers .
3. One way to think of Simulink is as a virtual analog computer.
4. Its strength is its ability to model dynamic systems—which are modelled mathematically as differential equations.

Getting Started

To start Simulink, open MATLAB and type simulink into the command window or select the Simulink icon from the Shortcut toolbar.

The Simulink Library Browser opens, showing the available libraries of blocks used to create a Simulink model.
To view the blocks, either select the library from the left-hand pane or double click on the icons in the right-hand pane.

To create a new model, select File ➞ New ➞ Model from the browser window.

Model 1

First model will simply add two numbers.
From the library, click and drag the constant block into the model window.
Repeat the process, so that there are two copies of constant block in the model.

Now drag the sum block into the model.
Draw connections between the constants and sum block by clicking and dragging between the ports.
To add a display, select and drag display block to model and connect it to output port of sum block.

The last thing we need to do before running the model is to adjust the simulation time, from the box on the menu bar.
Run the simulation by selecting the run button on the toolbar or by selecting Simulation ➞ Start from the menu bar.

Save this model in the usual way, by selecting File ➞ Save and adding an appropriate name.
The files are stored with the extension, .mdl.

Model 2

To solve differential equations with Simulink, create a model by dragging the appropriate blocks onto the model window, and connect them.
The blocks include; a clock, to generate times (Source library), a math function block, modified in the parameter window to square the block input (Math Operations library), a sum block (Commonly Used Blocks library), an integrator block (Continuous library), and a scope block (Sink library).
Connect all the blocks as shown in figure and the desired result is displayed.

A Simple GUI with One User Interaction

Creating a layout

1. To get started, select the guide icon from the toolbar, or type guide at the command line.

or


2. The GUIDE Quick Start window will open.


3. To start a new project, simply select the Blank GUI template, located in the list on the left-hand side of the window.
4. After that a new figure window—called the GUIDE layout editor—will open.


5. To create a layout of buttons, textboxes, and graphics windows, use the icons on the left-hand side of the window in the “component palette.”                                                                                                                                                                 6. To change the palette of tools to a list of the item names select File ➞ Preferences ➞ GUIDE then check “Show names in component palette.”

7. The Property Inspector is used to modify the design elements.
8. The Property Inspector can be accessed from the menu bar by selecting View ➞ Property Inspector
9. The Property Inspector lists a wide range of properties for the selected object in the GUIDE window.
10. One can change the font of the message displayed, change the color of the text box etc.
11. Use the same process to modify the properties of the “edit text” box.
12. The GUIDE window can be saved and run by selecting the Save and Run icon from the window toolbar.

Adding Code to M-File

1. The m-file is organized as a function, with multiple sub-functions.
2. Some of the subfunctions create the graphics in the saved window.
3. Others are reserved for adding the code that will cause an action when a user interacts with the GUI.
4. To see a list of the functions in the saved file, select the Show Functions icon on the toolbar.
5. The only functions a user should modify are labeled as:
gui_name_OpeningFcn
graphics_object_name_Callback

Callbacks

1. It allows the user to interact with the GUI.
2. Clicking on the function of interest will shows the corresponding section of code.
3. An alternative approach to find the appropriate sub-function to modify is to use the layout editor.
4. Right click on the graphics object, select View Callbacks, then select Callback.

get Function

1. When a user types in a textbox, the contents are stored as the string property.
2. To retrieve the information and use it in m-file, use the get function.

Run GUI

1. To run GUI, select the Save and Run icon from the m-file window or from the Guide layout editor.
2. To run the GUI, type a value into the edit window, and hit enter.
3. The opening function is the only other sub-function to be modified in this file.
4. It executes when the GUI first runs, and can be used to control how the figure window appears before the user starts adding data.

 

Data Structures

Introduction

1. Data structures are variables that store more than one value.
2. An array is a data structure in which all of the values are logically related.
3. A cell array is a kind of data structure that stores values of different types.
4. Cell arrays can be vectors or matrices; the different values are referred to as the elements of the array.
5. Structures are data structures that group together values that are logically related, but are not the same thing and not necessarily the same type.

Creating cell arrays

1. To create cell arrays curly braces are used instead of square brackets.
2. To create a row vector cell array, the values are separated by commas.
3. To create a column vector cell array, the values are instead separated by semicolons.
4. The type of cell arrays is cell.
5. Another method of creating a cell array is to simply assign values to specific array elements and build it up element by element.

Referring to and display elements

1. Using curly braces for the subscripts will reference the contents of a cell; called content indexing.

2. Using parentheses for the subscripts references the cells; this is called cell indexing.

3. The celldisp function displays the contents of all elements of the cell array.

4. To delete an element from a vector cell array or to delete an entire row or column, cell indexing is used.

Storing strings in cell arrays

1. As cell arrays can store different types of values, strings of different lengths can be stored in the elements.
2. The length of each string can be displayed using a for loop to loop through the elements of the cell array.

3. The function cellstr converts from a character array padded with blanks to a cell array in which the trailing blanks have been removed.

4. The char function can convert from a cell array to a character matrix.
5. The function iscellstr will return logical true if a cell array is a cell array of all strings or logical false if not.

Create and Modify Structure Variables

1. Creating structure variables can be accomplished by using the struct function.

2. An alternative method of creating structures is by using the dot operator to refer to the fields within the structure.

3. The disp function will display either the entire structure or an individual field.
4. By using fprintf, only individual fields can be printed.

5. The function rmfield removes a field from a structure.

Passing Structures to Functions

Related structure functions

1. The function isstruct will return logical 1 for true if the variable argument is a structure variable or 0 if not.
2. The isfield function returns logical true if a field name is a field in the structure argument or logical false if not.

3. The fieldnames function will return the names of the fields that are contained in a structure variable.

Vectors of Structures

1. In many applications, including database applications, information would normally be stored in a vector of structures, rather than in individual structure variables.

2. For loop can also be used to display each element in the packages vector.

 

 

 

String Manipulation

Introduction

1. A string in MATLAB consists of any number of characters and is contained in a single quotes.
2. Strings are vectors in which every element is a single character.
3. MATLAB also has built-in functions that are written specifically to manipulate strings.

Creating String Variables

1. A string consists of any number of characters (including, possibly, none). The following are examples of strings:
‘ ‘
‘X’
‘Cat’
‘Hello there’
‘123’
2. A substring is a subset or part of a string. For example, ‘there’ is a substring within the string ‘Hello there’.
3. Characters include letters of the alphabet, digits, punctuation marks, white space, and control characters.
4. Control characters are characters that cannot be printed, but accomplish a task.
5. White space characters include the space, tab, newline, and carriage return.
6. Leading blanks are blank spaces at the beginning of a string.
7. Trailing blanks are blank spaces at the end of a string.
8. There are several ways that string variables can be created.
9. By using an assignment statement.
10. By using ‘input’ function.

Strings as Vectors

1. Strings are treated as vectors of characters.
2. The number of characters in a string can be found by using the length function.

3. Expressions can refer to an individual element (a character within the string), or a subset of a string, or a transpose of a string.
4. A blank space in a string is a valid character within the string.

5. A character matrix can be created that consists of strings in every row.
6. The following is created as a column vector of strings, but the end result is that it is a matrix in which every element is a character.

7. With a character matrix one can refer to an individual element (a single character) or an individual row (one of the strings).
8. As rows within a matrix must always be the same length, the shorter strings must be padded with blanks so that all strings have the same length; otherwise, an error will occur.

Concatenation

1. It means to join strings together.

2. Note that the variable names (or strings) must be separated by a blank space in the brackets, but there is no space in between the strings when they are concatenated.                                                                                                                      3. The method of using the square brackets will concatenate all of the characters in the strings, including all leading and trailing blanks.
4. The strcat function, however, will remove trailing blanks (but not leading blanks) from strings before concatenating.

Customizing String

1. The blanks function will create a string consisting of n blank characters.
2. It is usually most useful to use this function when a number of blank spaces is desired in between.

3. The sprintf function will create a string in which the output is not suppressed so the value of the string variable is shown.

Removing White Space Characters

1. The deblank function will remove blank spaces (only trailing blanks) from the end of a string.

2. The strtrim function will remove both leading and trailing blanks from a string, but not blanks in the middle of the string.

Changing Case

MATLAB has two functions that convert strings to all uppercase letters, or lowercase, called upper and lower.

Comparing String

1. The function strcmp compares strings, character by character.

2. Note that for strings these functions are used to determine whether strings are equal to each other or not, not the equality operator ==.                                                                                                                                                                            3. The function strncmp compares only the first n characters in strings and ignores the rest.

4. The first two arguments are the strings to compare, and the third argument is the number of characters to compare (the value of n).

Finding Strings

1. The function strfind receives two strings as input arguments.
2. The general form is strfind(string, substring)
3. If there are no occurrences, the empty vector is returned.

Replacing Strings

1. The function strrep finds all occurrences of a substring within a string and replaces them with a new substring.
2. The format is:
strrep(string, oldsubstring, newsubstring)

Separating Strings

1. The strtok function breaks a string into two pieces.
2. The format is:
[token, rest] = strtok(string)
3. Alternate delimiters can be defined. The format
[token, rest] = strtok(string, delimeters)

Evaluating a String

The function eval is used to evaluate a string.

Example:

The “is” Function

1. The function “isspace” returns logical true for every character that is a whitespace character.
2. The “ischar” function will return logical true if the vector argument is a character vector, or logical false if not.

Conversion between String and Number

1. To convert numbers to strings there are two functions int2str for integers and num2str for real numbers (which also works with integers).

2. The function str2num does the reverse; it takes a string in which a number is stored and converts it to the type double.

Other Features

1. The sscanf function reads data from a string.
2. The strjust function justifies a string.
3. The mat2str function converts a matrix to a string.
4. The isstrprop function examines string properties.

 

 

Numerical Techniques

Linear Interpolation

Linear interpolation can be performed with the interp1 function.

Cubic Spline Interpolation

A smoother curve can be created by using the cubic spline interpolation technique, included in the interp1 function.

Linear Regression

1. The simplest way to model a set of data is as a straight line.
2. To plot the data, draw a straight line through the data points to get a rough model of the data’s behavior.
3. This process is sometimes called “eyeballing it”—meaning that no calculations were done, but it looks like a good fit.
4. It is seen that several of the points appear to fall exactly on the line, but others are off by varying amounts.
5. In order to compare the quality of the fit of this line to other possible estimates, the difference between the actual
y-value and the value calculated from the estimate has found.
6. This difference is called the residual.
7. The linear regression technique uses an approach called least squares fit to compare how well different equations model the behavior of the data.
8. It is accomplished with the polyfit function.

Polynomial Regression

1. It is used to get the best fit by minimizing the sum of the squares of the deviations of the calculated values from the data.
2. The polyfit function allows to do this easily.

Polyval Function

1. The polyval function requires two inputs.
2. The first is a coefficient array, such as that created by polyfit.
3. The second is an array of input values for which output values are calculated.

Basic Fitting Tools

1. To activate the curve-fitting tools, select Tools : Basic Fitting from the menu bar in the figure.
2. The basic fitting window opens on top of the plot.
3. By checking linear, cubic, and show equations, the plot is generated.

Curve Fitting Toolbox

To open the curve-fitting toolbox, type cftool in the command window.

 

 

 

Symbolic Mathematics

Introduction

1. MATLAB’s symbolic capability is based on the MuPad software, originally produced by SciFace Software.
2. SciFace was purchased by the Mathworks in2008.
3. The MuPad engine is part of the symbolic toolbox.
4. A MuPad notebook is created by typing mupad at command prompt.

Creating Symbolic Variables

1. Symbolic mathematics is used regularly in math, engineering, and science classes.
2. It is often preferable to manipulate equations symbolically before substituting values for variables.
3. Before solving any equation(s), there is a need to create some symbolic variables.
4. Simple symbolic variables can be created in two ways.
5. To create the symbolic variable x, type either
x = sym (‘x’)
Or
syms x
Both techniques set the character ‘x’ equal to the symbolic variable x .


6. Note that in the workspace window both x and y are listed as symbolic variables and the array size for each is 1 x 1.
7. The syms command is particularly convenient, because it can be used to create multiple symbolic variables at the same time.
8. The sym function can also be used to create either an entire expression or an entire equation.

Symbolic Plotting

1. The Ezplot function: The symbolic toolbox includes a group of functions that allow you to plot symbolic functions. The most basic is ezplot.

2. Other plots: The 3D surface plotting functions (ezmesh, ezmeshc, ezsurf, and ezsurfc) are used that mirror the functions used in numeric plotting options.

Differentiation

A function called diff is used to find the derivative of a symbolic expression.

Integration

A function called int is used to find the integral of a symbolic expression.

Differential Equation

1. Differential equations contain both the dependent variable and its derivative with respect to the independent variable.
2. The symbolic toolbox includes a function called dsolve that solves differential equations, that is, it solves for y in terms of t.

Convert Expressions to Functions

The matlabFunction function converts a symbolic expression into an anonymous function.

 

 

 

Mathematics

Introduction

1. There are various Math functions in MATLAB: exp, sqrt, log, etc.
2. Various statistics functions in MATLAB are: mean, max, min, std, etc.
3. MATLAB also offers lots of Trigonometric functions e.g., sin, cos, tan, etc.
4. Complex numbers are important in modelling and control theory which is defined as; z = a + ib or z = a + jb where imaginary unit (i/j) is i=√-1.
5. MATLAB represents polynomials as row arrays containing coefficients ordered by descending powers.

Simple Math Function 

Creates a function that calculates the following mathematical exp.
z=3x^2+√(x^2+y^2) +ln(x)

Test with different values of x and y.

Statistics

1. MATLAB has built-in functions for many statistics.
2. min and max functions also return the index of the smallest or largest value.
3. If there is more than one occurrence, it returns the first.
4. For matrices, the min and max functions operate columnwise by default.


5. The arithmetic mean of a data set is what is usually called the average of the values.
6. For a matrix, the mean function operates columnwise.
7. To find the mean of each row, the dimension of 2 is passed as the second argument to the function

8. Harmonic Mean: It is calculated by using harmmean function.
9. Geometric Mean: It is calculated by using geomean function.


10. Variance and standard deviation are ways of determining the spread of the data.
11. The built-in function to calculate the variance is called var.
12. The standard deviation can be found either as the sqrt of the variance or using std.


13. The mode of a data set is the value that appears most frequently.
14. The built-in function in MATLAB for this is called mode.


15. The median is defined only for a data set that has been sorted first, meaning that the values are in order.
16. The function in MATLAB is called median.

Set Operations

1. These include union, intersect, unique, setdiff, and setxor.
2. All of these functions can be useful when working with data sets.

3. The function ismember receives two vectors as input arguments, and returns a logical vector that is the same length as the first argument.
4. Contains logical 1 for true if the element in the first vector is alsoin the second, or logical 0 for false if not.

5. The issorted function will return logical 1 for true if the argument is sorted in ascending order (lowest to highest), or logical 0 for false if not.

Trigonometric Functions

Create various trigonometric functions and plot them on same figure.

Complex Numbers

Complex no. is defined as:
z = a + ib or z = a + jb
The complex conjugate of z is defined as:
z* = a – ib

Polynomials

It is expressed as:
p(x)=p1x^n+p2x^(n-1)+—+pn+pn+1
where p1,p2,p3,… are the coefficients of polynomial.
Polynomial,
p(x)=-5.45x^4+3.2x^2+8x+5.6 will be written as shown.

MATLAB Functions