You are on page 1of 20

ME 421 - LAB 1

INTRODUCTION TO

MATLAB, SIMULINK,
AND

DSPACE

Comments: This document is strongly complimented by a series of video tutorials produced by Math Works, the parent company of MatLab and Simulink. These tutorials can be found online at: http://www.mathworks.com/academia/student_center/tutorials/index. html?link=body Comments in the left margin will direct you to the appropriate videos or other references for each lesson. Activities are provided for the lessons so that you can test your understanding of the concepts presented. A writing icon indicates that you should record your work and turn it in to your TA for grading.

LESSON 1 THE MATLAB WORKSPACE


To open MatLab: Start >>All Programs >> MATLAB >>R2008a >> MATLAB R2008a
Navigating the MATLAB Desktop

Aside: When opening MatLab in the ME 421 Lab the following windows will open: Select dSPACE RTI Platform Support Select RTI1104 RTI Unsuitable Configuration Preferences Select Set Preferences Automatically

Slides 1-13
The layout of the MatLab desktop may be different from that in the tutorial but all of the windows discussed can be found.

Workspace: Current variables and data.

Other Useful Resources (optional) Working in the Development Environment

Current DirectoryShows contents of current directory

Command Window: Enter commands into MatLab

Command History:Records all past commands

Activity 1:
1. Create a folder to store your work 2. Open MatLab 3. Change directories to your new folder

ME 421 Lab 1 Page 1 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 2: BASIC MATLAB COMMANDS AND CONVENTIONS


Calculations in MatLab: - MatLab can be used as a calculator for basic and advanced calculations. - Commands to be used with scalar variables are shown below (vector and matrix variables will be covered later)
Addition Subtraction Exponent Imaginary Exponential Factorial x! ex a+b a-b a^b A+iB or A+jB pi exp(x) factorial(n) Multiplication Division Sci, Notation (a x 10b) Square Root Absolute Value Natural Log (ln x) Log base 10 (log x) a*b a\b a e b or a E b sqrt(n) abs(n) log(n) Log10(n)

MATLAB Fundamentals

Slides 16-25

Help in MatLab - doc opens MatLab documentation, doc command gives specific information about a specific command - help command gives information about the command in the command window - There are many online sources of information about MatLab. - There is more information in MathWorks video tutorials. - There are also text tutorials and forums on the MathWorks site. Variables: - All variables are arrays and can have a variety of dimensions. - Variables are double (16 digits of data) by default though they only display 5 (this can be changed using short/long commands) - Variables are created by assigning value on right of the equal sign to the variable name on the left. - Variable names must start with a letter but can contain letters, numbers, and underscores. They are case sensitive. Aside: Avoid assigning variables names that already have meaning in MatLab. To find out if your variable name (vname) has a meaning in MatLab use help vname.

ME 421 Lab 1 Page 2 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

Working with Variables: - Variables are listed in the Workspace window or can be listed using the whos command. - You can view and edit the contents of a variable using the variable editor that is opened when you double click on a variable in the Workspace window. - You can also enter a variables name in the command window to display its content. Other useful MatLab Commands:
<up arrow> diary fname diary on diary off Scrolls through past commands entered at the >> Very useful for repetitive entries or to correct minor mistakes Saves any new content in the command window to the file fname. Repeating the command appends to the end of the file (it does not overwrite). Diary on and off will toggle the diary on and off. If no fname is give the file will be saved to diary in the current directory Comment - everything on the same line following this sign is a comment and will not be evaluated. Allows you to continue your input on the next line if it gets long. Deletes the variable x from the workspace. clear all or clear will remove all variables. Lists current variables with details Ending an expression with ; hides the output Aborts the command that is executing

% ...
clear x whos

;
<ctrl C>

Activity 2:
1. Make a variable t with the value 0.4 and a variable x with a value of 2. 2. Use MatLab to evaluate the following expression.

v (sin(2 t) x )2 2 x e t

ME 421 Lab 1 Page 3 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 3: WORKING WITH MATRICES IN MATLAB


Vectors: - List of numbers o Column vector: down, separate numbers by ; o Row vector: across, separate numbers by , - Creating row vectors with equal spacing

MATLAB Fundamentals

Slides 26-30

Though not mentioned in the tutorial you can also create vectors by simply listing the values in []

Column vectors are transposes of row vectors: v_c=v_r

Importing and Extracting Data Slides 6-9

Matrixes: - 2-dimentional list of data - Create by listing numbers or by combining vectors or other matrixes. o Enter by row (elements separated by space or ,) and separate rows with ; Example: >> A = [5,4,3;8,7,6] A = 5 4 3 8 7 6 o Use vector or matrix names as elements (sizes must match) Special Matrixes
zeros(m,n) eye(m,n) ones(m,n) diag(v,k) rand(m,n) m by n matrix of zeros m by n identity matrix m by n matrix of ones Square matrix with v (a vector) as the kth diagonal and zeros elsewhere m by n matrix of random numbers chosen from a uniform distribution on the interval (0,1)

MATLAB Fundamentals Slides 31, 34-36

ME 421 Lab 1 Page 4

Extract data through the variable editor or index notation

Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

o In variable editor: select data, right click, select Create variable from Selection, name variable o Index notation: A(i,j) (i row, j column) Specify index or range of index (a:b) : means all possible indexes Example: A(4,:) all elements in the 4th row o Index notation: single index A(k) count starting at top left and moving down each column. o end specifies last element Matrix Math
Let A and B be matrices; v and u are vectors; and c and d are constants. A + c, v + c A c, v c A + B, v + u A B, v u A*c A/c A .* B, v.*u A ./ B, v./u A * B, v * u, A*v A.^c A^c Adds c to each element in the matrix or vector Subtracts c from each element in the matrix or vector Adds each element in A (or v) to the corresponding element in B (or u) (sizes must match) Subtracts each element in A (or v) to the corresponding element in B (or u) (sizes must match) Multiplies each element of A by c Divides each element of A by c Multiplies each element in A (or v) by the corresponding element in B (or u) (sizes must match) Multiplies each element in A (or v) by the corresponding element in B (or u) (sizes must match) Cross product of A and B (inner dimensions must agree) Takes each element times itself c times Finds the product of A times itself c times (A must be square)

Activity 3:
1. Create the row vector v1 = 2 4 6 8 using the equal spacing command and v2 = 1 4 7 10 using the linspace command. 2. Create the column vector v3 with the values 3 7 2 3. Use matrix math to find A, the cross product of v3 and v2 (Note: you will need to determine the correct order of v3 and v2 for this to work) 4. Use index notation to extract the following from A a. x = 8 b. v4 = 7 28 49 70 c. B = 28 49 8 14
ME 421 Lab 1 Page 5 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 4: INTRODUCTION TO MATLABS BUILT-IN FUNCTIONS


MatLab Functions: - Syntax: output = FunctionName(input) - Can use vectors and matrixes and inputs and outputs - Can have multiple inputs and outputs: [out1,out2] = FunctionName(in1, in2) Getting more Information: - Click on the function browser (fx) to see list of functions. - Use the following commands to get a list of functions:
doc elfun doc datafun doc elmat doc specfun helpwin Elementary mathematical functions Data analysis & statistical functions Matrix functions Specialized mathematical functions All functions available

Conducting Computational Analysis

Slides 1-13

doc commandname give help on a specific command

Examples of useful MatLab Functions:


max min size length round mean sum prod cumsum sort Finds maximum Finds minimum Finds size of matrix Finds length of vector Rounds to nearest integer Finds average Finds sum Finds product Finds cumulative sum Sorts the values

Many of these work on a vector or on each column in a matrix.

Activity 4:
1. Use the documentation to find out how the max command works. 2. Use the max command to find the maximum value in the following matrix A= 4 2 0 9 3. Use a MatLab Function to find the following x = 4 + 8 + 10 + 2 - 3

ME 421 Lab 1 Page 6 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 5: CREATING GRAPHS IN MATLAB


Making a Plot: - Use control-click to select your variables in the Workspace. Then select plot command from plot icon. - Use the command: plot(x,y) - Open a new figure with figure - Add to current graph with hold on or through plottools - Toggle the grid on and off with grid Working with Plots: - Use plot tools to edit graphs and add data

Visualizing Data

Slides 1-9

Other Useful Resources (optional) Visualizing Data Overview


Fitting Data to a Curve

Slides 1-6

Change display window Create m-file to re-create graph at later point with File -> Generate M-File From the command line add title, etc with title(text), xlabel(text), ylabel(text), legend(text) Include formatting in your plot(x,y) command (see doc for specifications) Put several sets of axes in the same window with subplot

Activity 5:
1. Create a plot of y=sin(2 x) where x goes from 0 to 2 in steps of 0.1. 2. Add a title and axis labels to your graph 3. Indicate one of the x-intercepts with an arrow and a label (hint use plot tools) 4. Plot z=cos(2 x) on the same plot as a red dashed line.

ME 421 Lab 1 Page 7 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 6:
M-FILES: SCRIPTS AND FUNCTIONS

Automating Analysis with Scripts Slides 1-15

General Information: - Scripts: group of MatLab commands - Functions: operates on inputs to produce outputs - Write programs in the MatLab editor (works like text editor)

Other Useful Resources (optional) Writing a MatLab Program -

Use same commands as in Command Window but will only execute at the end. Can be reused easily. Use comments (%) to clarify the program for future reference.

M-Files Scripts: - Collection of commands. - Save as name.m (m-file) - Run using the run button, double clicking the m-file in the Current Directory Window, or typing the script name in the Command Window

Programming in MatLab Slides 3-9

Variables created are available in the Workspace. Graphics will be created.

M-Files Functions: - First line must be the function declaration: function [out1,out2] = function_name(in1, in2) - Can take in any number of inputs and put out any number of outputs. - Save file with same name as function - Run function by calling it from the workspace or other m-file - Variables in function code do not need to match variable names in call statement. - Separate Workspace that is cleared on completion.

Activity 6:
1. Write a function that evaluates the expression below for any two inputs of t, and x

y 2sin2t 3x
ME 421 Lab 1 Page 8 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 7: FLOW CONTROL AND LOOPS IN MATLAB


Flow Control: if elseif else syntax: if condition1 == true statements1 elseif condition2 == true statements2 else statements3 end Logical and Relational Expressions - find more information with doc logical operators and doc relational operators - Common logical expressions
== ~= <, > <= >= Equal to Not Equal to Less than, greater than Less than or equal to, Greater than or equal to & | ~ all any and both true or either true not all are true any are true

Programming in MatLab

Slides 11-20

Loops: for and while


Using matrix math there are often ways to avoid loops completely.

while loop: run iterations until a condition is no longer true while condition1 == true runloop end -

for loop: repeat an operation for a given number of iterations for counter = range runloop end

Range can be any vector (ordered or unordered) but if counter is used and an index it must be a positive index. Exit loops with an if statement and the break command.

Activity 7:
1. Write code to calculate the following iterative expression where x goes from 0 to 10 in steps of h=0.1 and the initial value of y is 1. y j 1 y j hx j 2. Check the sizes of your x and y vectors. If necessary change your code so that they are the same size.

ME 421 Lab 1 Page 9 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 8: DIFFERENTIAL EQUATIONS IN MATLAB: ODE45


1st Order ODEs: - Rearrange ODE so that derivative is on the lhs and no derivatives are on the rhs - Use ode45 to solve
ODE45 Demo

Slides 1-6

odefun is the name of a function m-file that evaluates the function as rearranged in (1) and must have the declaration: function dx=odefun(t,x)

Ode45 can solve any ODE it does not need to be linear.

Higher Order ODEs - Need to rewrite as system of 1st order equations (1) Solve for the highest derivative (2) Rename as the 1st derivative of a dummy variable (3) Integrate the expression in (2) (4) If (3) isnt first order repeat (2) & (3) (5) Substitute so that lhs are first derivatives and there are no derivatives on the rhs. - Use ode45 with vector inputs - The order in the vectors needs to be consistent - Yout will be a matrix - select the correct column based on the order of the vector.

Activity 8:
1. Use ode45 to solve the following 1st order differential equation from 0 to 5sec. (Hint: this is the same expression as in Activity 6 if y=dx so you can use the function you wrote there) plot the results.

15 x 10 sin 2t 5x

x0

2. Write the following as a system of 1st order equations. (No code needed hand work is ok)

3 7x x 12 x x
ME 421 Lab 1 Page 10

5 sin( 2 t )

Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 9: SIMULINK OVERVIEW


Simulink Overview: - Graphical programming environment in MatLab - Open by typing simulink in command window or with the Simulink button.
Constructing and Running a Simple Model

Slides 8-18, 25 Block Library:


Continuous: Blocks useful with ODEs

Math Operations: Math functions

Sinks: Output blocks Sources: Input blocks

Useful Blocks:
1 Gain

Gain multiply by a constant Add or subtract input signals Multiplies or divides signals Applies the given function to the input Integrates the input
Sine Wave

Creates plot of the signal Outputs time Creates a step function.


Step

Add

Creates a ramp function Creates a sine function

ME 421 Lab 1 Page 11 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

Making a Block Diagram: - Create an new diagram

Drag block from library into diagram Join blocks by drawing signal connections from output-ports to input-ports Double click a block to change parameters and get more information Label a block and signal connection by clicking on label or double clicking on connection. Turn a block by right clicking and selecting format, Save a model using the save button. Recall it by typing its name in the workspace (from correct directory) or double clicking the model in the Current Directory Window.

Activity 9:
1. Code the following equation in Simulink.

y 25sin(2t ) 4 t 2
2. Attach a scope output block 3. Label your blocks and signal connections appropriately

ME 421 Lab 1 Page 12 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 10: RUNNING A SIMULATION IN SIMULINK


Run the simulation: - Click the run button
Simulating a Model

Slides 27-36

Adjust the stop time in the stop time box. A stop time of Inf will give you a continuous run. You can stop the simulation with the stop button.

View Results: - Double click on the scope to view the results. - Auto-scale the axis with the binoculars button.

Changing Run Parameters: - Menu Simulation Configuratons Parameters Solver - Common changes: step size, solver type (ode45, etc) Finding Help: - Help buttons in Configuration Parameters - Help on each block parameter screen - Simulink Documentation

Activity 10:
1. Run the simulink model you created in Activity 9. 2. Use the scope to view your results include a screen shot of this plot. 3. Change the solver parameters to determine the step size that causes the output to no long look realistic (include thisincorrect plot).

ME 421 Lab 1 Page 13 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 11: INTERFACING SIMULINK AND MATLAB


Importing Data from MatLab: - Allows for easy modification of variables - From Workspace source (enter a variable name, iname) o iname must be 2 column matrix: column 1 is time and column 2 is the signal that is defined in the workspace Exporting Data to MatLab: - To Workspace sink block (with output variable name, oname) - Make sure that the block is set as an array - Get time vector from clock and output with Workspace sink block Modifying Paramters from MatLab (not discussed in video) - Enter a variable name in any parameter block. - Define variable value in MatLab Workspace. Running Simulink Models from the Command Window: - Use the command: sim(model_name)

Working with MatLab

Slides 38 - 47

Activity 11:
1. Replace the scopes in the Simulink model in Activity 9 & 10 with To Workspace outputs. 2. Change the model so that the multiplication factor 4 is now a variable M defined in MatLab 3. Write a MatLab script that a. Assigns a value to M b. Runs the Simulink model c. Plots the results of y vs time

ME 421 Lab 1 Page 14 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 12: DIFFERENTIAL EQUATIONS IN SIMULINK


Modeling ODEs: - Integrating blocks o In continuous library o Need one for each order of derivatives o Can set initial condition as parameter - Steps: (1) Solve ODE for highest order derivative (2) Add integrator blocks (3a) Add summing block and create appropriate input ports (3b) Construct the right hand side of equation using the available derivatives and other Simulink blocks (4) Input initial conditions into each integration block (5) Define constants in MatLab and run the model

Modeling a System of Differential Equations

Slides 21 - 27

Some ODEs have forcing functions. These can be incorporated using source blocks.

Activity 12:
1. Use simulink to numerically solve the following differential equation below from 0-5 sec.

15 x 10 sin 2t 5x

x0

2. Output the results to MatLab and create a plot of the results. 3. How do these results compare to the results generated by ode45 in Activity 8?

ME 421 Lab 1 Page 15 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 13: INTRODUCTION TO DSPACE


dSpace Overiview: - Data acquisition system that works with simulink - Real-time control capability through simulink dSpace Hardware:
dSpace Tutorial
Inputs: ADCH5-8 Outputs: DACH1-4

Creating a Simulink model for dSpace:


ADC: Brings an input signal that is collected by dSpace into simulink.

DAC: Sends a signal created in simulink to be output through dSpace

Create Simulink model and use ADC and DAC ports to interface with dSpace.

Activity 13:
1. Create a Simulink diagram that: a. Outputs a sine wave to dSpace through DACH 2 b. Collects data from dSpace through ADCH 8 and sends it to a scope. 2. Get approval of your model from your supervisor before proceeding to the next lesson.
ME 421 Lab 1 Page 16 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 14: SETTING UP THE CONTROL DESK


Steps to creating a Control Desk experiment: (1) Create a simulink diargram using dSpace input and output ports (2) Open the dSpace Control Desk
dSpace Tutorial

(3) Create a new experiment (4) Create a new layout (5) Build the simulink model (6) Create the control desk layout - Select desired instrument and draw box for location & size - Must include a CaptureSettings box to collect data (7) Link your model variable to the instruments& plots in the layout - Find appropriate simulink block in model tab - Drag variable/parameter name from model tab to instrument. (8) Add all open files to experiment (9) Save experiment Steps to reusing an old Control Desk experiment: (1) Open experiment file (2) Click on the model tab right click in lower left panel select load application (3) Trouble shooting: a. If there is no model lab: Re-make the simulink model b. Correct any broken links between instruments and variables.

Activity 14:
1. Create a Control Desk Experiment that works with your simulink model from Activity 13 and has the following properties: a. Allows you to the change the frequency and amplitude of the sine wave output (use NumericInput box). b. Shows plots of both the sine wave output and the input. c. Runs for 10 seconds. d. Records data for the input channel. 2. Turn in a screen shot of your Control Desk layout 3. Save your experiment and associated files

ME 421 Lab 1 Page 17 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 15: RUNNING AN EXPERIMENT AND COLLECTING DATA


Running a Control Desk experiment: - Switch to the animation mode. - If it doesnt start automatically Start button. Important Note: Even when the Control Desk experiment is not running there will still be a signal coming out of the dSpace board. Set your output amplitude to 0 when you are finished. Saving Data: - Press the save button and enter and file name for your data. Do not use names that start with a number - MatLab cant open them.

press the

dSpace Tutorial

Activity 15:
1. Connect your dSpace output port to the oscilloscope to check your output. 2. Connect the signal generator to your dSpace input port to provide data to collect.

3. Run your Control Desk experiment 4. Output a sine wave with an amplitude of 1.5 V and a frequency of 6.3 rad/sec and use the oscilloscope to verify this output (Note: the oscilloscope measures frequency in Hz). Save your oscilloscope data and include it in your activity report. 5. Use the signal generator to create a sawtooth wave with an amplitude of 1 V and a frequency of 1 Hz. Collect this data with dSpace and record it to a file.

ME 421 Lab 1 Page 18 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

LESSON 16: WORKING WITH DSPACE DATA IN MATLAB


Loading Data: - Import Wizard interactive right click on file in Current Directory window and select import data - Command depending on file format (see doc fileformats) Extracting General Data: - Variable Editor select desired data right click Create Variable from Selection - Index notation in Command window (see Lesson3) Extracting dSpace Data: - dSpace data is saved as a structure. - Access the data through variable editor - From command line >> time = fname.X(1,1).Data; >>var1 = fname.Y(1,1).Data; >>var2 = fname.Y(1,2).Data; Saving Data: - Select variables in Workspace right click select Save As - save command

Importing and Extracting Data

Slides 1-5, (6-9), 10-12

Activity 16:
1. Use matlab to open the data you collected in Activity 15. 2. Plot it as a green line with appropriate title and axis labels.

ME 421 Lab 1 Page 19 Developed by Dr. LeAnn Faidley, Mechanical Engineering, Iowa State University, Spring 2009

You might also like