Presentation is loading. Please wait.

Presentation is loading. Please wait.

Simulation And Modelling

Similar presentations


Presentation on theme: "Simulation And Modelling"— Presentation transcript:

1 Simulation And Modelling
Prepared by- Sabbir Muhammad Saleh Lecturer (00627) University of South Asia Mob Mail-

2 Introduction to MATLAB
Engineering H192 Winter 2005 Introduction to MATLAB Instructor notes: This is the first set of slides for Matlab in the H192 C/C++ programming course. It provides an overview of information that will be helpful in getting started working with Matlab and in the Matlab environment. Lecture 18

3 Reading Data from files
Engineering H192 Winter 2005 Reading Data from files MATLAB supports reading an entire file and creating a matrix of the data with one statement. >> load mydata.dat; % loads file into matrix. % The matrix may be a scalar, a vector, or a % matrix with multiple rows and columns. The % matrix will be named mydata. >> size (mydata) % size will return the number % of rows and number of % columns in the matrix >> length (myvector) % length will return the total % no. of elements in myvector Instructor notes: The load function is convenient for reading into Matlab the entire contents of a file and storing the contents in a matrix all in one command. The matrix created to store the data will have the same name as the file, minus any extension on the file. There are a decent number of options that accompany the load command which you can read about using >> help load. It’s important that the file being loaded either be in the same directory in which Matlab is currently working, or that the directory where the file is stored be in Matlab’s search path, or that the necessary pathname be included along with the file name when invoking the load command. The size function returns the number of rows and columns in a matrix. Again, there are other options that you can see using >> help size, but the most important thing is that size returns the number of rows and columns in a matrix. The length function returns the number of elements in a vector. It’s interesting to note that length will also work on a matrix and will return the greater of the row length or the column length. Lecture 18

4 Plotting with MATLAB * (horizontal axis)
Engineering H192 Winter 2005 Plotting with MATLAB MATLAB will plot one vector vs. another. The first one will be treated as the abscissa* (or x) vector and the second as the ordinate (or y) vector. The vectors have to be the same length. MATLAB will also plot a vector vs. its own index. The index will be treated as the abscissa vector. Given a vector “time” and a vector “dist” we could say: >> plot (time, dist) % plotting versus time >> plot (dist) % plotting versus index Instructor notes: Matlab’s plotting capabilities are one of its most powerful and convenient features. Typically the plot () command takes two arguments with the first being the abscissa and the second being the ordinate. The vectors must be of the same length. If only one argument is provided, then Matlab treats that argument as the ordinate and uses the index of each element of the vector as the abscissa. The plot () command is fairly flexible. It is probably a good idea to have students in the mode of doing >> help plot so that they can see the other options that are available with plot (). For example, you can control the type of line or data point being displayed as well as its color. Most generally the plot () command is written as plot (x1, y1, s1, x2, y2, s2, ...) where the x’s are abscissa vectors, the y’s are ordinate vectors, and the s’s are strings contained within single quotes that specify the plotting options for the preceding (x, y) vector pair. When plot () is used with multiple sets of arguments, a single plot window is opened and all of the data are displayed on the same plot.  * (horizontal axis) Lecture 18

5 Engineering H192 Winter 2005 Plotting with MATLAB There are commands in MATLAB to "annotate" a plot to put on axis labels, titles, and legends. For example: >> % To put a label on the axes we would use: >> xlabel ('X-axis label') >> ylabel ('Y-axis label') >> % To put a title on the plot, we would use: >> title ('Title of my plot') Instructor notes: As would be expected, there are commands for putting axis labels and titles and legends and text on plots. For the most part, these commands take as an argument a string. The legend () command has a numbered list of positions on the page that can be an additional argument. Use >> help legend to see a list of these. This can be done via the command line as the slide indicates or they can be done interactively from the plot window. So, a student could quickly plot the data, if desired, and then using the icons once the plot window has opened he or she could add the desired title, legend, labels, etc. It is probably most useful to become comfortable using the command line commands, but other options do exist. Again it would be good to point out the >> help plot because doing so will return the names of the plot annotating commands. Lecture 18

6 Engineering H192 Winter 2005 Plotting with MATLAB Vectors may be extracted from matrices. Normally, we wish to plot one column vs. another. If we have a matrix “mydata” with two columns, we can obtain the columns as a vectors with the assignments as follows: >> first_vector = mydata ( : , 1) ; % First column >> second_vector = mydata ( : , 2) ; % Second one >> % and we can plot the data >> plot ( first_vector , second_vector ) Instructor notes: As we have seen, vectors can be extracted from matrices. If we had a matrix with two columns of data in it, we could extract two vectors of data from the matrix, in this case column vectors, and then use the plot () command to plot the data. Note that it’s not necessary to create the two vectors. mydata(:,1) could be used as the first argument to plot and mydata(:,2) could be used as the second argument, if desired. Lecture 18

7 Some Useful MATLAB commands
Engineering H192 Winter 2005 Some Useful MATLAB commands who List known variables whos List known variables plus their size Help Ex: >> help sqrt Help on using sqrt lookfor Ex: >> lookfor sqrt Search for keyword sqrt in m-files what Ex:>> what a: List MATLAB files in a: clear Clear all variables from work space clear x y Clear variables x and y from work space clc Clear the command window Instructor notes: The next two slides list some useful commands. Who will return the names of all the variables currently in the Matlab workspace. Whos will provide the same information as well as the amount of storage set aside for each variable...that is, their size. The help command is very useful and will return help information on how to use any of the built in Matlab functions. The syntax is help function_name. Another good use of help will come when students begin to create their own Matlab functions. They should not create functions that have the same name as built in Matlab functions. If they do, then the functionality of the built in function will be lost until Matlab is restarted. They can perform a >> help function_name and if Matlab returns help info, they will know that the function already exists as a built in. The lookfor and what commands are useful for Matlab specific files. what searches for Matlab files on a given drive or in a given path. lookfor searches the first comment line of Matlab specific files for the given string and then, if a match is found, displays that first comment line. The clear command removes variables from memory. If clear is supplied with variable names, then only those variables will be removed. It’s a good idea to tell students to type carefully when using clear with arguments. They may want to only clear one variable, but if you hit the <ENTER> key before you get a chance to name the variable, all the variables in memory will be cleared and they may have to start a significant amount of work over. The clc command removes all typing and Matlab output from the command window, but does not do anything to the variables currently stored in the Matlab workspace. clc is particularly useful to clear extraneous information out of the command window prior to doing a problem whose results the students would like to print. Lecture 18

8 Some Useful MATLAB commands
Engineering H192 Winter 2005 Some Useful MATLAB commands what List all m-files in current directory dir List all files in current directory ls Same as dir type test Display test.m in command window delete test Delete test.m cd a: Change directory to a: chdir a: Same as cd pwd Show current directory which test Display current directory path to test.m Instructor notes: More useful commands...what without a drive specified, as on the previous slide, lists all of the m-files in the current directory. The topic of m-files came up on the previous slide very briefly, too. Maybe this is a good time to point out that m-files are essentially Matlab programs and that the students will be dealing with them in the near future as they write small programs that are very much like C/C++ programs. dir and ls list the contents of the current directory. Of course, you can specify a path after the dir or ls and the contents of the directory specified in the path will be displayed. type will display the file specified on the command line in the command window. delete will remove the appropriate file. cd and chdir will allow you to change directories to the one specified following the command. In addition, there are icons at the top of the Matlab window that will allow you to do the same thing. One small window should indicate the present working directory, which is also determined by entering the pwd command in the command window. There is a drop down menu available immediately next to the small window displaying the present working directory that, when click on, will display all recently used directories. This allows for quick transfer between directories. Additionally, the ellipsis icon next to the present working directory window allows for more complete navigation to other directories. The which command followed by a filename displays the path to the specified file. Lecture 18

9 MATLAB Relational Operators
Engineering H192 Winter 2005 MATLAB Relational Operators MATLAB supports six relational operators. Less Than < Less Than or Equal <= Greater Than > Greater Than or Equal >= Equal To == Not Equal To ~= Instructor notes: Matlab has six relational operators that are used in making comparisons just like in C/C++. It is probably a good thing to emphasize to the students that the relational operators in Matlab are the same as they are in C/C++ EXCEPT for “not equal to” which uses the ~ instead of the ! as part of the operator. Students should be reminded to pay close attention to which language they’re writing in on exams so that they do not mix the two. Lecture 18

10 MATLAB Logical Operators
Engineering H192 Winter 2005 MATLAB Logical Operators MATLAB supports three logical operators. not ~ % highest precedence and & % equal precedence with or or | % equal precedence with and Instructor notes: In addition to the relational operators, Matlab has three logical operators, not, and, and or. A couple differences from C/C++ that are important. First, rather than using the ! for not as in C/C++, the ~ is used. Given the information on the previous slide, this is no surprise. The second difference is that in C/C++ when using logical operators && is a logical and operator and & is a bitwise operator, likewise || is a logical or operator and | is a bitwise operator. However, in Matlab, & and | are logical operators. Lecture 18

11 MATLAB Logical Functions
Engineering H192 Winter 2005 MATLAB Logical Functions MATLAB also supports some logical functions. xor (exclusive or) Ex: xor (a, b) Where a and b are logical expressions. The xor operator evaluates to true if and only if one expression is true and the other is false. True is returned as 1, false as 0. any (x) returns 1 if any element of x is nonzero all (x) returns 1 if all elements of x are nonzero isnan (x) returns 1 at each NaN in x isinf (x) returns 1 at each infinity in x finite (x) returns 1 at each finite value in x Instructor notes: This slide describes some logical functions that Matlab has available. The xor function performs an exclusive or operation on the two logical expressions that it takes as arguments. Thus, xor returns true if and only if one of the expressions is true and the other expression is false. As the slide indicates, true is a 1 and false is a 0. Other logical functions include any, all, isnan, isinf, and finite. any returns true if any element in the item being evaluated is nonzero and all returns true if all of the elements in the item being evaluated are nonzero. isnan, isinf, and finite each return a true at each element in the item being evaluated that is not a number (NaN), infinite, or finite, respectively. Lecture 18

12 MATLAB Display formats
Engineering H192 Winter 2005 MATLAB Display formats MATLAB supports 8 formats for outputting numerical results. format long 16 digits format short e 5 digits plus exponent format long e 16 digits plus exponent format hex hexadecimal format bank two decimal digits format + positive, negative or zero format rat rational number (215/6) format short default display Instructor notes: This list describes the display formats that exist in Matlab. The important thing to note here is that the format command only affects the display, it does not affect how values are actually stored. So, there is no benefit in memory to using format short over format long, for example. This list leaves out format compact and format loose which remove and put back in extra line feeds, respectively. The default is format loose. Lecture 18

13 Matlab Selection Structures
Engineering H192 Winter 2005 Matlab Selection Structures An if - elseif - else structure in MATLAB. Note that elseif is one word. if expression1 % is true % execute these commands elseif expression2 % is true else % the default end Instructor notes: Like C/C++ Matlab has an if-elseif-else structure for decision making or branching. There are a few differences between Matlab and C/C++. In Matlab, elseif is one word, rather than two, as it is in C/C++. Curly brackets are not used in Matlab at all, and the end of the if-elseif-else block is denoted with end. Just like in C/C++ expressions are evaluated to be true or false and when an expression evaluates to true, then the statements that correspond to that section of the block are executed. Parentheses are not required around the expression being evaluated. Lecture 18

14 MATLAB Repetition Structures
Engineering H192 Winter 2005 MATLAB Repetition Structures A for loop in MATLAB for x = array for x = 1: 0.5 : 10 % execute these commands end A while loop in MATLAB while expression while x <= 10 % execute these commands Instructor notes: Again, as in C/C++ Matlab has looping structures. Matlab has a for loop that is very much like C/C++’s, but with some slight differences. Curly brackets are not needed in Matlab’s for loop. The counter variable is initialized at the beginning of the loop in an assignment statement. Colons are used to separate the initial value from the increment and end point, respectively. If no increment is specified, then it is assumed to be 1. The end statement marks the end of the while loop. The while loop in Matlab is also much like in C/C++, but with some differences. No curly brackets are needed in Matlab and the end of the loop is denoted with the end statement. Matlab does not have a do-while loop like C/C++. It might be a good idea to point out that often in Matlab loops that access arrays begin with 1 rather than 0 as they normally do in C/C++. This is because the first index in a Matlab array is 1 while the first index in a C/C++ array is 0. Lecture 18

15 Scalar - Matrix Addition
Engineering H192 Winter 2005 Scalar - Matrix Addition EDU» a=3; EDU» b=[1, 2, 3;4, 5, 6] b = EDU» c= b+a % Add a to each element of b c = 7 8 9 Instructor notes: The next four slides deal with scalar-matrix math, addition, subtraction, multiplication, and division. In scalar-matrix math the scalar and each individual element of the matrix interact based on the operation being performed. So, if a scalar is being added to a matrix, that scalar will be added to each element in the matrix resulting in a matrix of the same dimensions with each element being modified by the sum of the element and the scalar. Remember, addition and multiplication are commutative, so the order of the operation does not matter. Subtraction and division are not commutative. Also, Matlab will not allow you to divide the scalar by the matrix. It will return an error message indicating that the matrix dimensions do not match. Lecture 18

16 Scalar - Matrix Subtraction
Engineering H192 Winter 2005 Scalar - Matrix Subtraction EDU» a=3; EDU» b=[1, 2, 3;4, 5, 6] b = EDU» c = b - a %Subtract a from each element of b c = Instructor notes: Lecture 18

17 Scalar - Matrix Multiplication
Engineering H192 Winter 2005 Scalar - Matrix Multiplication EDU» a=3; EDU» b=[1, 2, 3; 4, 5, 6] b = EDU» c = a * b % Multiply each element of b by a c = Instructor notes: c = b * a will produce the same results. Lecture 18

18 Scalar - Matrix Division
Engineering H192 Winter 2005 Scalar - Matrix Division EDU» a=3; EDU» b=[1, 2, 3; 4, 5, 6] b = EDU» c = b / a % Divide each element of b by a c = Instructor notes: c = a/b will produce an error message. Lecture 18

19 Transferring Data from Class (R:) to temp
When using MATLAB in Windows XP, g16.dat is on Class drive (R:) under ENG_H192. Do a file transfer by drag and drop to temp directory cd to \temp in MATLAB load g16.dat to produce a matrix called g16 Create two vectors from the g16 two column matrix Plot vector2 vs vector1

20 Thank You


Download ppt "Simulation And Modelling"

Similar presentations


Ads by Google