Prepared by: Khairul Anuar Ishak Department of Electrical, Electronic & System Engineering Faculty of Engineering Universiti Kebangsaan Malaysia

Size: px
Start display at page:

Download "Prepared by: Khairul Anuar Ishak Department of Electrical, Electronic & System Engineering Faculty of Engineering Universiti Kebangsaan Malaysia"

Transcription

1 MATLAB Tutorial of Fundamental Programming Prepared by: Khairul Anuar Ishak Department of Electrical, Electronic & System Engineering Faculty of Engineering Universiti Kebangsaan Malaysia

2 MATLAB tutorial of fundamental programming Preface This tutorial introduces the fundamental ideas for programming in MATLAB. The objective is to help you at solving the kinds of mathematical problems that you will likely encounter as an engineering student, as well as a researcher. It requires no prior knowledge of MATLAB or programming experience but if you have a strong background in mathematics and computer programming then you can quickly learn how MATLAB can help you with your course work and design projects. However, for those of you who are just starting out learning MATLAB, then this tutorial is for you. Remember, it is assumed throughout all chapters that you are following along, using MATLAB and entering all commands shown. The questions and answers of the exercises, will be given during the workshop went off. On completion of the workshop, participants should be able to: Use MATLAB to solve certain mathematical problems. Produce a simple MATLAB program files (m-files). Use MATLAB effectively and also being ready to explore more of MATLAB on your own. Enjoy the MATLAB! ;-) Notes: You can me if you have any problems or corrections about these pieces of code, or if you would like to add your own tips to those described in this document. Khairul Anuar Ishak nuarscc@yahoo.com i

3 MATLAB tutorial of fundamental programming Contents 1 Introduction to MATLAB 1 What is MATLAB? 1 MATLAB System 2 The Advantages of MATLAB 2 Disadvantages of MATLAB 3 2 Getting Started 4 Starting MATLAB 4 Ending a Session 8 3 MATLAB Basics 9 Variables and Arrays 9 Arithmetic Operations 14 Common MATLAB Functions 16 4 Plotting and Visualization 17 Plotting in MATLAB 17 Images in MATLAB 24 5 Programming 25 Data Types 25 M-File Programming 27 Flow Control 30 ii

4 CHAPTER 1: Introduction to MATLAB CHAPTER 1 Introduction to MATLAB What is MATLAB? What is MATLAB? MATLAB (short for MATrix LABoratory) is a special-purpose computer program optimized to perform engineering and scientific calculations. It is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to-use environment where problems and solutions are expressed in familiar mathematical notation. Typical uses include: Math and computation Algorithm development Modelling, simulation and prototyping Data analysis, exploration and visualization Scientific and engineering graphics Application development, including Graphical User Interface (GUI) building MATLAB is an interactive system whose basic data element is an array that does not require dimensioning. This allows you to solve many technical computing problems, especially those with matrix and vector formulations, in a fraction of the time it would take to write a program in a scalar non-interactive language such as C, C++ or Fortran. MATLAB has evolved over a period of years with input from many users. In university environments, it is the standard instructional tool for introductory and advanced courses in mathematics, engineering and science. In industry, MATLAB is the tool of choice for highproductivity research, development and analysis. MATLAB features a family of application-specific solution called Toolboxes. Very important to most users of MATLAB, toolboxes allow you to learn and apply specialized technology. Toolboxes are comprehensive collections of MATLAB function (m-files) that extend the MATLAB environment to solve particular classes of problems. Areas in which toolboxes are available include signal processing, control systems, neural networks, fuzzy logic, wavelets, image processing, simulation and many others. 1

5 CHAPTER 1: Introduction to MATLAB MATLAB System MATLAB System The MATLAB system consists of five main parts: 1. The MATLAB language. This is a high-level matrix/array language with control flow statements, functions, data structures, input/output, and object-oriented programming features. It allows both programming in the small to rapidly create quick and dirty throw-away programs, and programming in the large to create complete large and complex application programs. 2. The MATLAB working environment. This is the set of tools and facilities that you work with as the MATLAB user or programmer. It includes facilities for managing the variables in your workspace and importing and exporting data. It also includes tools for developing, managing, debugging, and profiling M-files, MATLAB s applications. 3. Handle Graphics. This is the MATLAB graphics system. It includes high-level commands for two-dimensional and three-dimensional data visualization, image processing, animation, and presentation graphics. It also includes low-level commands that allow you to fully customize the appearance of graphics as well as to build complete Graphical User Interfaces on your MATLAB applications. 4. The MATLAB mathematical function library. This is a vast collection of computational algorithms ranging from elementary functions like sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms. 5. The MATLAB Application Program Interface (API). This is a library that allows you to write C and Fortran programs that interact with MATLAB. It include facilities for calling routines from MATLAB (dynamic linking), calling MATLAB as a computational engine, and for reading and writing MAT-files. The Advantages of MATLAB MATLAB has many advantages compared to conventional computer languages for technical problem solving. Among them are: 1. Ease of Use. MATLAB is an interpreted language. Program may be easily written and modified with the built-in integrated development environment and debugged with the MATLAB debugger. Because the language is so easy to use, it is ideal for the rapid prototyping of new programs. 2. Platform Independence. MATLAB is supported on many different computer systems, providing a large measure of platform independence. At the time of this writing, the language is supported on Windows NT/2000/XP, Linux, several versions of UNIX and the Macintosh. 3. Predefined Function. MATLAB comes complete with an extensive library of predefined functions that provide tested and pre-packaged solutions to many basic technical tasks. For examples, the arithmetic mean, standard deviation, median, etc. these and hundreds of other functions are built right into the MATLAB language, making your job much easier. In addition to the large library of function built into the basic MATLAB language, 2

6 CHAPTER 1: Introduction to MATLAB Disadvantages of MATLAB there are many special-purpose toolboxes available to help solve complex problems in specific areas. There is also an extensive collection of free user-contributed MATLAB programs that are shared through the MATLAB Web site. 4. Device-Independent Plotting. Unlike most other computer languages, MATLAB has many integral plotting and imaging commands. The plots and images can be displayed on any graphical output device supported by the computer on which MATLAB is running. 5. Graphical User Interface. MATLAB includes tools that allow a programmer to interactively construct a graphical user interface, (GUI) for his or her program. With this capability, the programmer can design sophisticated data-analysis programs that can be operated by relatively inexperienced users. 6. MATLAB Compiler. MATLAB s flexibility and platform independence is achieved by compiling MATLAB programs into a device-independent p-code, and then interpreting the p-code instructions at runtime. Unfortunately, the resulting programs can sometimes execute slowly because the MATLAB code is interpreted rather than compiled. Disadvantages of MATLAB MATLAB has two principal disadvantages. The first is that it is an interpreted language and therefore can execute more slowly than compiled languages. This problem can be mitigated by properly structuring the MATLAB program, and by the use of the MATLAB compiler to compile the final MATLAB program before distribution and general use. The second disadvantage is cost: a full copy of MATLAB is five to ten times more expensive than a conventional C or Fortran compiler. This relatively high cost is more than offset by then reduced time required for an engineer or scientist to create a working program, so MATLAB is cost-effective for businesses. However, it is too expensive for most individuals to consider purchasing. Fortunately, there is also an inexpensive Student Edition of MATLAB, which is a great tool for students wishing to learn the language. The Student Edition of MATLAB is essentially identical to the full edition. 3

7 CHAPTER 2: Getting Started CHAPTER 2 Getting Started Starting MATLAB Starting MATLAB You can start MATLAB by double-clicking on the MATLAB icon or invoking the application from the Start menu of Windows. The main MATLAB window, called the MATLAB Desktop, will then pop-up and it will look like this: Figure 2.1: The Default MATLAB desktop When MATLAB executes, it can display several types of windows that accept commands or display information. It integrates many tools for managing files, variables and applications within the MATLAB environment. The major tools within or accessible from the MATLAB desktop are: 1. The Current Directory Browser 2. The Workspace Window 3. The Command Window 4. The Command History Window 5. The Start Button 6. The Help Window 4

8 CHAPTER 2: Getting Started Starting MATLAB If desired, this arrangement can be modified by selecting an alternate choice from [View] [Desktop Layout]. By default, most MATLAB tools are docked to the desktop, so that they appear inside the desktop window. However, you can choose to undock any or all tools, making them appear in windows separate from the desktop. The Command Window Figure 2.2: The Command Window The Command Window is where the command line prompt for interactive commands is located. Once started, you will notice that inside the MATLAB command window is the text: To get started, select MATLAB Help from the Help menu. >> Click in the command window to make it active. When a window becomes active, its titlebar darkens. The >> is called the Command Prompt, and there will be a blinking cursor right after it waiting for you to type something. You can enter interactive commands at the command prompt (>>) and they will be executed on the spot. As an example, let s enter a simple MATLAB command, which is the date command. Click the mouse where the blinking cursor is and then type date and press the ENTER key. MATLAB should then return something like this: >> date ans = 01-Sep-2006 Where the current date should be returned to you instead of 01-Sep Congratulation! You have just successfully executed your first MATLAB command! 5

9 CHAPTER 2: Getting Started Starting MATLAB The Command History Window Figure 2.3: The Command History Window The Command History Window, contains a log of commands that have been executed within the command window. This is a convenient feature for tracking when developing or debugging programs or to confirm that commands were executed in a particular sequence during a multistep calculation from the command line. The Current Directory Browser Figure 2.4: The Directory Browser The Current Directory Browser displays a current directory with a listing of its contents. There is navigation capability for resetting the current directory to any directory among those set in the path. This window is useful for finding the location of particular files and scripts so that they can be edited, moved, renamed or deleted. The default directory is the Work subdirectory of the original MATLAB installation directory. 6

10 CHAPTER 2: Getting Started Starting MATLAB The Workspace Window Figure 2.5: The Workspace Window The Workspace Window provides an inventory of all the items in the workspace that are currently defined, either by assignment or calculation in the Command Window or by importing with a load or similar command from the MATLAB command line prompt. These items consist of the set of arrays whose elements are variables or constants and which have been constructed or loaded during the current MATLAB session and have remained stored in memory. Those which have been cleared and no longer are in memory will not be included. The Workspace Window shows the name of each variable, its value, its array size, its size in bytes, and the class. Values of a variable or constant can be edited in an Array Editor which is launched by double clicking its icon in the Workspace Window. The Help Window Figure 2.6: The Help Window 7

11 CHAPTER 2: Getting Started Ending a Session You can access the online help in one of several ways. Typing help at the command prompt will reveal a long list of topics on which help is available. Just to illustrate, try typing help general. Now you see a long list of general purpose MATLAB commands. In addition, you can also get help on the certain command. For example, date command. The output of help also refers to other functions that are related. In this example the help also tells you, See also NOW, CLOCK, DATENUM. You can now get help on these functions using the three different commands as well. >> help date DATE Current date as date string. S = DATE returns a string containing the date in dd-mmm-yyyy format. See also NOW, CLOCK, DATENUM. There is a much more user-friendly way to access the online help, namely via the MATLAB Help Browser. Separate from the main desktop layout is a Help desktop with its own layout. This utility can be launched by selecting [Help] [MATLAB Help] from the Help pull down menu. This Help desktop has a right side which contains links to help with functions, help with graphics, and tutorial type documentation. The Start Button The Start Button (see figure 2.1) allows a user to access MATLAB tools, desktop tools, help files, etc. it works just like the Start button on a Windows desktop. To start a particular tool, just click on the Start Button and select the tool from the appropriate sub-menu. Interrupting Calculations If MATLAB is hung up in a calculation, or is just taking too long to perform an operation, you can usually abort it by typing [CTRL + C] (that is, hold down the key labeled CTRL, and press C). Ending a Session One final note, when you are all done with your MATLAB session you need to exit MATLAB. To exit MATLAB, simply type quit or exit at the prompt. You can also click on the special symbol that closes your windows (usually an in the upper right-hand corner). Another way to exit is by selecting [File] [Exit MATLAB]. Before you exit MATLAB, you should be sure to save any variables, print any graphics or other files you need, and in general clean up after yourself. 8

12 CHAPTER 3: MATLAB Basics CHAPTER 3 MATLAB Basics Variables and Arrays Variables and Arrays The fundamental unit of data in any MATLAB program is the array. An array is a collection of data values organized into rows and columns and known by a single name. Individual data values within an array are accessed by including the name of the array followed by subscripts in parentheses that identify the row and column of the particular value. Even scalars are treated as arrays by MATLAB they are simply arrays with only one row and one column. There are three fundamental concepts in MATLAB, and in linear algebra, are scalars, vectors and matrices. 1. A scalar is simply just a fancy word for a number (a single value). 2. A vector is an ordered list of numbers (one-dimensional). In MATLAB they can be represented as a row-vector or a column-vector. 3. A matrix is a rectangular array of numbers (multi-dimensional). In MATLAB, a twodimensional matrix is defined by its number of rows and columns. a =10 b = 1 [ 2 3 4] 1 c = 2 3 This is a scalar, containing 1 element This is a 1 4 array containing 4 elements, known as a row vector This is a 3 1 array containing 3 elements, known as a column vector 1 d = This is a 3 3 matrix, containing 9 elements In MATLAB matricies are defined inside a pair of square braces ([]). Punctuation marks of a comma (,), and semicolon (;) are used as a row separator and column separator, respectfully. You can also use a space as a row separator, and a carriage return (the ENTER key) as a column separator as well. 9

13 CHAPTER 3: MATLAB Basics Variables and Arrays Examples 3.1 Below are examples of how a scalar, vector and matrix can be created in MATLAB. >> my_scalar = my_scalar = >> my_vector1 = [1, 5, 7] my_vector1 = >> my_vector2 = [1; 5; 7] my_vector2 = >> my_vector1 = [1 5 7] my_vector1 = >> my_vector2 = [1 5 7] my_vector2 = >> my_matrix = [ ; 7 3 2; ; 8 1 1] my_matrix = Indexing into an Array Once a vector or a matrix is created you might needed to extract only a subset of the data, and this is done through indexing. Row 1 A 2-by-3 Matrix Row 2 Col 1 Col 2 Col 3 Figure 3.1: An array is a collection of data values organized into rows and columns 10

14 CHAPTER 3: MATLAB Basics Variables and Arrays Individual elements in an array are addressed by the array name followed by the row and column of the particular element. If the array is a row or column vector, then only one subscript is required. For example, according to the example 3.1: o my_vector2(2) is 5 o my_matrix(3,2) is 4 or my_matrix(7) is 4 The Colon Operator The colon (:) is one of MATLAB s most important operators. It occurs in several different forms. Examples To create an incremental or a decrement vector >> my_inc_vec1 = [1:7] my_inc_vec1 = [ ] >> my_inc_vec2 = [1:2:7] my_inc_vec2 = [ ] >> my_dec_vec = [5:-2:1] my_dec_vec = [ 5 3 1] 2. To refer portions of a matrix/vector >> my_matrix = [ ; 7 3 2; ; 8 1 1] my_matrix = >> new_matrix1 = my_matrix(1:3,2:3) new_matrix1 = >> new_matrix2 = my_matrix(2:4,:) new_matrix2 = NOTES: If the colon is used by itself within subscript, it refers to all the elements in a row or column of a matrix! 11

15 CHAPTER 3: MATLAB Basics Concatenating Matrices Variables and Arrays Matrix concatenation is the process of joining one or more matrices to make a new matrix. The expression C = [A B] horizontally concatenates matrices A and B. The expression C = [A; B] vertically concatenates them. Examples 3.3 >> A = [8 19; 7 2]; >> B = [1 64; 4 5; 3 78]; >> C = [A; B] C = Reshaping a Matrix Here are a few examples to illustrate some of the ways you can reshape matrices. Examples 3.4 Reshape 3-by-4 matrix A to have dimensions 2-by-6. >> A = [ ; ; ] A = >> B = reshape(a, 2, 6) B =

16 CHAPTER 3: MATLAB Basics Variables and Arrays Examples 3.5 Transpose A so that the row elements become columns or vice versa. You can use either the transpose function or the transpose operator ( ). To do this: >> A = [ ; ; ]; >> B = A B = General Function for Matrix and Vector There are many MATLAB features which cannot be included in these introductory notes. Listed below are some of the MATLAB functions regard to matrix and vector. Basic Vector Function MATLAB includes a number of built-in functions that you can use to determine a number of characteristics of a vector. The following are the most commonly used such functions. size length min max sum sort abs Returns the dimensions of a matrix Returns the number of elements in a matrix Returns the minimum value contained in a matrix Returns the maximum value contained in a matrix Returns the sum of the elements in a matrix Returns the sorted elements in a matrix Returns the absolute value of the elements in a matrix Examples 3.6 The following example demonstrates the use some of these functions. >> A = [ ]; >> sza = size(a) sza = 1 4 >> lena = length(a) lena = 4 >> mna = min(a) mna = 1 >> mxa = max(a) mxa = 4 >> suma = sum(a) suma = 10 >> sta = sort(a) sta =

17 CHAPTER 3: MATLAB Basics Arithmetic Operations Functions to Create a Matrix This following section summarizes the principal functions used in creating and handling matrices. Most of these functions work on multi-dimensional arrays as well. diag cat ones zeros rand repmat Create a diagonal matrix from a vector Concatenate matrices along the specified dimension Create a matrix of all ones Create a matrix of all zeros Create a matrix of uniformly distributed random numbers Create a new matrix by replicating or tiling another Examples 3.7 The following example demonstrates the use some of these functions. >> A = zeros(2,4) A = >> B = 7*ones(1,3) >> C = rand(4,3) C = B = Arithmetic Operations MATLAB can be used to evaluate simple and complex mathematical expressions. When we move from scalars to vectors (and matrices), some confusion arises when performing arithmetic operations because we can perform some operations either on an element-by-element (array operation) or matrices as whole entities (matrix operation). Expressions use familiar arithmetic operators: Array Operators Operation MATLAB Form Comments Addition A + B Array addition is identical Subtraction A - B Array subtraction is identical Multiplication A.* B Element-by-element multiplication of A and B. Both arrays must be the same shape, or one of them must be a scalar Division A./ B Element-by-element division of A and B. Both arrays must be the same shape, or one of them must be a scalar 14

18 CHAPTER 3: MATLAB Basics Arithmetic Operations Power A.^ B Element-by-element exponentiation of A and B. Both arrays must be the same shape, or one of them must be a scalar Examples 3.8 The following example demonstrates the use some of these operations. >> A = [ ; ; ] A = >> B = [ ; ; ] >> A = [ ]; >> B = A.^2 B = >> A = [ 2 4 ; 8 10] A = B = >> B = [2 4; 2 5] B = >> C = A.*B C = >> C = A./B C = Matrix Operators Operation MATLAB Form Comments Addition A + B Array addition is identical Subtraction A - B Array subtraction is identical Multiplication A * B Matrix multiplication of A and B. The number of columns in A must equal the number of rows in B. Division A / B Matrix division defined by A * inv(b), where inv(b) is the inverse of matrix B. Power A ^ B Matrix exponentiation of A and B. The power is computed by repeated squaring Examples 3.9 >> A = [ 2 4 ; 8 10]; >> B = [2 4; 2 5]; >> C = A*B C = >> A = [ 2 4 ; 8 10]; >> B = [2 4; 2 5]; >> C = B*A C =

19 CHAPTER 3: MATLAB Basics Common MATLAB Functions Built-in Variables MATLAB uses a small number of names for built-in variables. An example is the ans variable, which is automatically created whenever a mathematical expression is not assigned to another variable. Table below lists the built-in variables and their meanings. Although you can reassign the values of these built-in variables, it is not a good idea to do so, because they are used by the built-in functions. Variable ans eps i,j pi realmax realmin Inf NaN Meaning Value of an expression when that expression is not assigned to a variable Floating-point precision Unit imaginary number, i = j = 1 π, Largest positive floating-point number Smallest positive floating-point number 1, a number larger than realmax, the result of evaluating 0 0 Not a number, (e.g., the result of evaluating 0 Examples 3.10 >> x = 0; >> 5/x Warning: Divide by zero ans = Inf >> x = 0; >> x/x Warning: Divide by zero ans = NaN Common MATLAB Functions A few of the most common and useful MATLAB functions are shown in table below. These functions will be used in many times. It really helps you when one needs to manage variables and workspace and to perform an elementary mathematical operation. Managing Variables and Workspace who whos clear disp clc demo List current variables List current variables, long form Clear variables and functions from memory Display matrix or text Clear command window Run demonstrations 16

20 CHAPTER 3: MATLAB Basics Common MATLAB Functions Examples 3.11 >> whos Name Size Bytes Class ans 1x1 226 sym object y 1x1 8 char array v 4x5 200 double array x 1x3 500 double array >> str = [ MATLAB Baguss..! ]; >> disp(str); MATLAB Baguss..! Built-in Function of Elementary Math abs(x) Calculates x angle(x) Returns the phase angle of the complex value x, in radians exp(x) x Calculates e mod(x) Remainder or modulo function log(x) Calculates the natural logarithm log e x sqrt(x) Calculates the square root of x sin(x) Calculates the sin(x), with x in radians cos(x) Calculates the cos(x), with x in radians tan(x) Calculates the tan(x), with x in radians ceil(x) Rounds x to the nearest integer towards positive infinity fix(x) Rounds x to the nearest integer towards zero floor(x) Rounds x to the nearest integer towards minus infinity round(x) Rounds x to the nearest integer Examples 3.12 >> z = 2*sin(pi/2)+log(2) z = >> z = round(z) z = 3 >> z = 2*sin(pi/2)+log(2) z = >> z = round(z) z = 3 17

21 CHAPTER 4: Plotting and Visualization CHAPTER 4 Plotting and Visualization Plotting in MATLAB Plotting in MATLAB MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs. This section describes a few of the most important graphics functions and provides examples of some typical applications. Creating a Plot The plot function has different forms, depending on the input arguments. If y is a vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of the elements of y. If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x. For example, to plot the value of the sine function from zero to 2π, use: Creating Line Plots Examples 4.1 >> x = 0:pi/100:2*pi; >> y = sin(x); >> plot(x,y); 18

22 CHAPTER 4: Plotting and Visualization Plotting in MATLAB This is the basic command of plotting a graph. Besides that, MATLAB has commands which will let you add titles and labels and others in order to make your figures more readable. However, you need to keep the figure window open while executing these commands. >> xlabel( Radian ); >> ylabel( Amplitude ); >> title( Plot of sin(x) vs x ); >> grid on; The current limits of this plot can be determined from the basic axis function. So, in order to modify the x-axis within [0 2π], you need to run this function: >> axis([0 2*pi -1 1]); 19

23 CHAPTER 4: Plotting and Visualization Plotting in MATLAB Annotating Plots You can adjust the axis tick-mark locations and the labels appearing at each tick mark. For example, this plot of the sine function relabels the x-axis with more meaningful values. Example 4.2 >> x = 0:pi/100:2*pi; >> y = sin(x); >> plot(x,y); >> set(gca, XTick,-pi:pi/2:pi); >> set(gca, XTickLabel,{ -pi, -pi/2, 0, pi/2, pi }); >> xlabel('-\pi \leq \Theta \leq \pi'); >> ylabel('sin(\theta)'); >> title('plot of sin(\theta)'); Creating a Semilogarithmic Plot Semilogarithmic plot is another type of figuring a graph by rescaling if the new data falls outside the range of the previous axis limits. Example 4.3 >> x = linspace(0,3); >> y = 10*exp(-2*x); >> semilogy(x,y); >> grid on; 20

24 CHAPTER 4: Plotting and Visualization Plotting in MATLAB Specifying the Color and Size of Lines You can control a number of line style characteristics by specifying values for line properties. LineWidth Width of the line in units of points MarkerEdgeColor Color of the marker or the edge color for filled markers MarkerFaceColor Color of the face of filled markers MarkerSize Size of the marker in units of points Example 4.4 >> x = -pi:pi/10:pi; >> y = tan(sin(x)) - sin(tan(x)); >> plot(x,y,'--rs','linewidth',2,... 'MarkerEdgeColor','k',... 'MarkerFaceColor','g','MarkerSize',10); Multiple Plots Often, it is desirable to place more than one plot in a single figure window. This is achieved by three ways: The subplot Function The subplot Function breaks the figure window into an m-by-n matrix of small subplots and selects the ith subplot for the current plot. The plots are numbered along the top row of the figure window, then the second row, and so forth. 21

25 CHAPTER 4: Plotting and Visualization Plotting in MATLAB Example 4.5 >> x = linspace(0,2*pi); >> subplot(2,2,1); >> plot(x,sin(x)); >> >> subplot(2,2,2) >> plot(x,sin(2*x)); >> >> subplot(2,2,3) >> plot(x,sin(3*x)); >> >> subplot(2,2,4) >> plot(x,sin(4*x)); Multiple plots You can assign different line styles to each data set by passing line style identifier strings to plot and placing a legend on the plot to identify curves drawn with different symbol and line types. Example 4.6 >> x = linspace(0,2*pi); >> y1 = sin(x); >> y1 = cos(x); >> y1 = tan(x); >> plot(x,y1,x); >> axis([0 2*pi -1 1]); The hold Function The hold command will add new plots on top of previously existing plots. Example 4.6 >> x = -pi:pi/20:pi; >> y1 = sin(x); >> y2 = cos(x); >> plot(x,y1,'b-'); >> hold on; >> plot(x,y2,'g--'); >> hold off; >> legend('sin(x)','cos(x)'); 22

26 CHAPTER 4: Plotting and Visualization Plotting in MATLAB Line Plots in Three-Dimensions Now, the three-dimension analog of the plot function is plot3. if x, y and z are three vectors of the same length, plot3(x,y,z) generates a line in 3-D through the points whose coordinates are the elements of x, y and z and then produces a 2-D projection of that line on the screen. Example 4.7 >> Z = [0 : pi/50 : 10*pi]; >> X = exp(-.2.*z).*cos(z); >> Y = exp(-.2.*z).*sin(z); >> plot3(x,y,z,'linewidth',2); >> grid on; >> xlabel('x-axis'); >> ylabel('y-axis'); >> zlabel('z-axis'); Three-Dimensional Surface Mesh Plots The first step in displaying a function of two variables, z = f(x,y), is to generate X and Y matrices consisting of repeated rows and columns, respectively, over the domain of the function. Then use these matrices to evaluate and graph the function. Meshgrid function transforms the domain specified by two-vectors, x and y, into matrices X and Y. Example 4.8 >> [X,Y] = meshgrid(-8:.5:8); >> R = sqrt(x.^2 + Y.^2); >> Z = sin(r)./r; >> mesh(x,y,z); 23

27 CHAPTER 4: Plotting and Visualization Images in MATLAB Images in MATLAB The basic data structure in MATLAB is the array, an ordered set of real or complex elements. Thus, MATLAB stores most images as two-dimensional arrays (i.e., matrices), in which each element of the matrix corresponds to a single pixel in the displayed image. For example, an image composed of 200 rows and 300 columns or different colored dots would be stored in MATLAB as a 200-by-300 matrix. Some images, such as RGB, require a threedimensional array, where the first plane in the third dimension represents the red pixel intensities, the second plane represents the green pixel intensities, and the third plane represents the blue pixel intensities. This example reads an 8-bit RGB image into MATLAB and converts it to a grayscale image. Example 4.9 >> rgb_img = imread('ngc6543a.jpg'); >> image(rgb_img); >> pause; >> graysc_img = rgb2gray(rgb_img); >> imshow(graysc_img); 24

28 CHAPTER 5: Programming CHAPTER 5 Programming Data Types Data Types There are many different types of data that you can work with in MATLAB. You can build matrices and arrays of floating point and integer data, characters and strings, logical true and false states, etc. you can also develop your own data types using MATLAB classes. Two of the MATLAB data types, structures and cell arrays, provide a way to store dissimilar types of data in the same array. There are 15 fundamental data types (or classes) in MATLAB. Each of these data types is in the form of an array. This array is a minimum of 0-by-0 in size and can grow to an n-dimensional array of any size. Two-dimensional versions of these arrays are called matrices. All of the fundamental data types are shown in lowercase text in the diagram below. Additional data types are user-defined, object-oriented user classes (a subclass of structure), and java classes, that you can use with the MATLAB interface to Java. Matrices of type double and logical may be either full or sparse. For matrices having a small number of nonzero elements, a sparse matrix requires a fraction of the storage space required for an equivalent full matrix. Sparse matrices invoke special methods especially tailored to solve sparse problems. ARRAY (full or sparse) logical char NUMERIC CELL structure Java Classes Function handle int8, unit8, int16, uint16, int32, uint32, int64, uint64 single double 25

29 CHAPTER 5: Programming The following table describes these data types in more detail. Data type Example Description int8, unit8, int16, uint16, int32, uint32, int64, uint64 int16(100) Signed and unsigned integer arrays that are 8, 16, 32, and 64 bits in length. Enables you to manipulate integer quantities in a memory efficient manner. These data types cannot be used in mathematical operations. char 'Hello' Character array (each character is 16 bits long). This array is also referred to as a string. logical magic(4) > 10 Logical array. Must contain only logical 1 (true) and logical 0 (false) elements. (Any nonzero values converted to logical become logical 1.) Logical matrices (2-D only) may be sparse. single 3*10^38 Single-precision numeric array. Single precision requires less storage than double precision, but has less precision and a smaller range. This data type cannot be used in mathematical operations. double 3*10^ i cell {17 'hello' eye(2)} structure a.day = 12; a.color = 'Red'; a.mat = magic(3); function Double-precision numeric array. This is the most common MATLAB variable type. Double matrices (2-D only) may be sparse. Cell array. Elements of cell arrays contain other arrays. Cell arrays collect related data and information of a dissimilar size together. Structure array. Structure arrays have field names. The fields contain other arrays. Like cell arrays, structures collect related data and information together. Handle to a MATLAB function. A function handle can be passed in an argument list and evaluated using feval user class inline('sin(x)') MATLAB class. This user-defined class is created using MATLAB functions. java class java.awt.frame Java class. You can use classes already defined in the Java API or by a third party, or create your own classes in the Java language. 26

30 CHAPTER 5: Programming M-File Programming MATLAB provides a full programming language that enables you to write a series of MATLAB statements into a file and then execute them with a single command. You write your program in an ordinary text file, giving the file a name of filename.m. The term you use for filename becomes the new command that MATLAB associates with the program. The file extension of.m makes this a MATLAB M-file. M-files can be scripts that simply execute a series of MATLAB statements, or they can be functions that also accept arguments and produce output. You create M-files using a text editor, then use them as you would any other MATLAB function or command. The process looks like this: Kinds of M-files There are two kinds of M-files Script M-files Do not accept input arguments or return output arguments Operate on data in the workspace Useful for automating a series of steps you need to perform many times Function M-files Can accept input arguments and return output arguments Internal variables are local to the function by default Useful for extending the MATLAB language for you application 27

31 CHAPTER 5: Programming Scripts Scripts are the simplest kind of M-file because they have no input or output arguments. They're useful for automating series of MATLAB commands, such as computations that you have to perform repeatedly from the command line. Scripts operate on existing data in the workspace, or they can create new data on which to operate. Any variables that scripts create remain in the workspace after the script finishes so you can use them for further computations. Example 5.1 % An M-file script to produce % Comment lines % "flower petal" plots theta = -pi:0.01:pi; % Computations rho(1,:) = 2*sin(5*theta).^2; rho(2,:) = cos(10*theta).^3; rho(3,:) = sin(theta).^2; for k = 1:3 polar(theta,rho(k,:)) % Graphics output pause end Try entering these commands in an M-file called petals.m. This file is now a MATLAB script. Typing petals at the MATLAB command line executes the statements in the script. 28

32 CHAPTER 5: Programming Functions Functions are M-files that accept input arguments and return output arguments. They operate on variables within their own workspace. This is separate from the workspace you access at the MATLAB command prompt. Example 5.2 function y = average(x) % AVERAGE Mean of vector elements. % AVERAGE(X), where X is a vector, is the mean of vector elements. % Nonvector input results in an error. [m,n] = size(x); if (~((m == 1) (n == 1)) (m == 1 & n == 1)) error('input must be a vector') end y = sum(x)/length(x); % Actual computation If you would like, try entering these commands in an M-file called average.m. The average function accepts a single input argument and returns a single output argument. To call the average function, enter >> z = 1:99; >> average(z) ans = 50 The Function Definition Line The function definition line informs MATLAB that the M-file contains a function, and specifies the argument calling sequence of the function. The function definition line for the average function is 29

33 CHAPTER 5: Programming All MATLAB functions have a function definition line that follows this pattern. The Function Name - MATLAB function names have the same constraints as variable names. The name must begin with a letter, which may be followed by any combination of letters, digits, and underscores. Making all letters in the name lowercase is recommended as it makes your M-files portable between platforms. Flow Control MATLAB has several flow control constructs: If 1. if 2. continue 3. break 4. switch and case 5. for 6. while The if statement evaluates a logical expression and executes a group of statements when the expression is true. The optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, which matches the if, terminates the last group of statements. The groups of statements are delineated by the four keywords--no braces or brackets are involved. IF expression statements ELSEIF expression statements ELSE statements END Continue The continue statement passes control to the next iteration of the for or while loop in which it appears, skipping any remaining statements in the body of the loop. In nested loops, continue passes control to the next iteration of the for or while loop enclosing it. Break The break statement lets you exit early from a for or while loop. In nested loops, break exits from the innermost loop only. 30

34 CHAPTER 5: Programming Switch and Case The switch statement executes groups of statements based on the value of a variable or expression. The keywords case and otherwise delineate the groups. Only the first matching case is executed. There must always be an end to match the switch. SWITCH expression CASE expression statements CASE expression statements OTHERWISE statements END For The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements. FOR variable = expression Statements,... Statements END While The while loop repeats a group of statements an indefinite number of times under control of a logical condition. A matching end delineates the statements. WHILE expression Statements END 31

Introduction to MATLAB

Introduction to MATLAB ELG 3125 - Lab 1 Introduction to MATLAB TA: Chao Wang (cwang103@site.uottawa.ca) 2008 Fall ELG 3125 Signal and System Analysis P. 1 Do You Speak MATLAB? MATLAB - The Language of Technical Computing ELG

More information

Chapter 1 Introduction to MATLAB

Chapter 1 Introduction to MATLAB Chapter 1 Introduction to MATLAB 1.1 What is MATLAB? MATLAB = MATrix LABoratory, the language of technical computing, modeling and simulation, data analysis and processing, visualization and graphics,

More information

MATLAB Tutorial EE351M DSP. Created: Thursday Jan 25, 2007 Rayyan Jaber. Modified by: Kitaek Bae. Outline

MATLAB Tutorial EE351M DSP. Created: Thursday Jan 25, 2007 Rayyan Jaber. Modified by: Kitaek Bae. Outline MATLAB Tutorial EE351M DSP Created: Thursday Jan 25, 2007 Rayyan Jaber Modified by: Kitaek Bae Outline Part I: Introduction and Overview Part II: Matrix manipulations and common functions Part III: Plots

More information

2.0 MATLAB Fundamentals

2.0 MATLAB Fundamentals 2.0 MATLAB Fundamentals 2.1 INTRODUCTION MATLAB is a computer program for computing scientific and engineering problems that can be expressed in mathematical form. The name MATLAB stands for MATrix LABoratory,

More information

Introduction to MATLAB

Introduction to MATLAB Introduction to MATLAB 1 Introduction to MATLAB A Tutorial for the Course Computational Intelligence http://www.igi.tugraz.at/lehre/ci Stefan Häusler Institute for Theoretical Computer Science Inffeldgasse

More information

Introduction to MatLab. Introduction to MatLab K. Craig 1

Introduction to MatLab. Introduction to MatLab K. Craig 1 Introduction to MatLab Introduction to MatLab K. Craig 1 MatLab Introduction MatLab and the MatLab Environment Numerical Calculations Basic Plotting and Graphics Matrix Computations and Solving Equations

More information

Introduction to MATLAB. Computational Probability and Statistics CIS 2033 Section 003

Introduction to MATLAB. Computational Probability and Statistics CIS 2033 Section 003 Introduction to MATLAB Computational Probability and Statistics CIS 2033 Section 003 About MATLAB MATLAB (MATrix LABoratory) is a high level language made for: Numerical Computation (Technical computing)

More information

! The MATLAB language

! The MATLAB language E2.5 Signals & Systems Introduction to MATLAB! MATLAB is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-to -use environment. Typical

More information

Introduction to Matlab

Introduction to Matlab Introduction to Matlab By:Mohammad Sadeghi *Dr. Sajid Gul Khawaja Slides has been used partially to prepare this presentation Outline: What is Matlab? Matlab Screen Basic functions Variables, matrix, indexing

More information

Introduction to MATLAB

Introduction to MATLAB Introduction to MATLAB Contents 1.1 Objectives... 1 1.2 Lab Requirement... 1 1.3 Background of MATLAB... 1 1.4 The MATLAB System... 1 1.5 Start of MATLAB... 3 1.6 Working Modes of MATLAB... 4 1.7 Basic

More information

PART 1 PROGRAMMING WITH MATHLAB

PART 1 PROGRAMMING WITH MATHLAB PART 1 PROGRAMMING WITH MATHLAB Presenter: Dr. Zalilah Sharer 2018 School of Chemical and Energy Engineering Universiti Teknologi Malaysia 23 September 2018 Programming with MATHLAB MATLAB Environment

More information

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing SECTION 1: INTRODUCTION ENGR 112 Introduction to Engineering Computing 2 Course Overview What is Programming? 3 Programming The implementation of algorithms in a particular computer programming language

More information

Matlab Lecture 1 - Introduction to MATLAB. Five Parts of Matlab. Entering Matrices (2) - Method 1:Direct entry. Entering Matrices (1) - Magic Square

Matlab Lecture 1 - Introduction to MATLAB. Five Parts of Matlab. Entering Matrices (2) - Method 1:Direct entry. Entering Matrices (1) - Magic Square Matlab Lecture 1 - Introduction to MATLAB Five Parts of Matlab MATLAB is a high-performance language for technical computing. It integrates computation, visualization, and programming in an easy-touse

More information

Introduction to MATLAB

Introduction to MATLAB to MATLAB Spring 2019 to MATLAB Spring 2019 1 / 39 The Basics What is MATLAB? MATLAB Short for Matrix Laboratory matrix data structures are at the heart of programming in MATLAB We will consider arrays

More information

Introduction to Engineering gii

Introduction to Engineering gii 25.108 Introduction to Engineering gii Dr. Jay Weitzen Lecture Notes I: Introduction to Matlab from Gilat Book MATLAB - Lecture # 1 Starting with MATLAB / Chapter 1 Topics Covered: 1. Introduction. 2.

More information

MATLAB. Miran H. S. Mohammed. Lecture 1

MATLAB. Miran H. S. Mohammed. Lecture 1 MATLAB Miran H. S. Mohammed 1 Lecture 1 OUTLINES Introduction Why using MATLAB Installing MATLAB Activate your installation Getting started Some useful command Using MATLAB as a calculator 2 INTRODUCTION

More information

Lecturer: Keyvan Dehmamy

Lecturer: Keyvan Dehmamy MATLAB Tutorial Lecturer: Keyvan Dehmamy 1 Topics Introduction Running MATLAB and MATLAB Environment Getting help Variables Vectors, Matrices, and linear Algebra Mathematical Functions and Applications

More information

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER BENC 2113 DENC ECADD 2532 ECADD LAB SESSION 6/7 LAB

More information

Getting started with MATLAB

Getting started with MATLAB Sapienza University of Rome Department of economics and law Advanced Monetary Theory and Policy EPOS 2013/14 Getting started with MATLAB Giovanni Di Bartolomeo giovanni.dibartolomeo@uniroma1.it Outline

More information

A Quick Tutorial on MATLAB. Zeeshan Ali

A Quick Tutorial on MATLAB. Zeeshan Ali A Quick Tutorial on MATLAB Zeeshan Ali MATLAB MATLAB is a software package for doing numerical computation. It was originally designed for solving linear algebra type problems using matrices. It's name

More information

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial 1 Matlab Tutorial 2 Lecture Learning Objectives Each student should be able to: Describe the Matlab desktop Explain the basic use of Matlab variables Explain the basic use of Matlab scripts Explain the

More information

Interactive Computing with Matlab. Gerald W. Recktenwald Department of Mechanical Engineering Portland State University

Interactive Computing with Matlab. Gerald W. Recktenwald Department of Mechanical Engineering Portland State University Interactive Computing with Matlab Gerald W. Recktenwald Department of Mechanical Engineering Portland State University gerry@me.pdx.edu Starting Matlab Double click on the Matlab icon, or on unix systems

More information

AMS 27L LAB #2 Winter 2009

AMS 27L LAB #2 Winter 2009 AMS 27L LAB #2 Winter 2009 Plots and Matrix Algebra in MATLAB Objectives: 1. To practice basic display methods 2. To learn how to program loops 3. To learn how to write m-files 1 Vectors Matlab handles

More information

Matlab Tutorial 1: Working with variables, arrays, and plotting

Matlab Tutorial 1: Working with variables, arrays, and plotting Matlab Tutorial 1: Working with variables, arrays, and plotting Setting up Matlab First of all, let's make sure we all have the same layout of the different windows in Matlab. Go to Home Layout Default.

More information

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP)

MATLAB Tutorial. Digital Signal Processing. Course Details. Topics. MATLAB Environment. Introduction. Digital Signal Processing (DSP) Digital Signal Processing Prof. Nizamettin AYDIN naydin@yildiz.edu.tr naydin@ieee.org http://www.yildiz.edu.tr/~naydin Course Details Course Code : 0113620 Course Name: Digital Signal Processing (Sayısal

More information

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain Introduction to Matlab By: Dr. Maher O. EL-Ghossain Outline: q What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display Facilities Flow Control

More information

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline (Cont d) MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An CSE 170 Interacting with MATLAB Instructor: Aijun An Department of Computer Science and Engineering York University aan@cse.yorku.ca Outline Starting MATLAB MATLAB Windows Using the Command Window Some

More information

Finding MATLAB on CAEDM Computers

Finding MATLAB on CAEDM Computers Lab #1: Introduction to MATLAB Due Tuesday 5/7 at noon This guide is intended to help you start, set up and understand the formatting of MATLAB before beginning to code. For a detailed guide to programming

More information

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

Outline. CSE 1570 Interacting with MATLAB. Starting MATLAB. Outline. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An. CSE 170 Interacting with MATLAB Instructor: Aijun An Department of Computer Science and Engineering York University aan@cse.yorku.ca Outline Starting MATLAB MATLAB Windows Using the Command Window Some

More information

Eng Marine Production Management. Introduction to Matlab

Eng Marine Production Management. Introduction to Matlab Eng. 4061 Marine Production Management Introduction to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment. Matlab is available

More information

Finding, Starting and Using Matlab

Finding, Starting and Using Matlab Variables and Arrays Finding, Starting and Using Matlab CSC March 6 &, 9 Array: A collection of data values organized into rows and columns, and known by a single name. arr(,) Row Row Row Row 4 Col Col

More information

Introduction to Matlab

Introduction to Matlab Introduction to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment. Matlab is available for PC's, Macintosh and UNIX systems.

More information

Introduction to MATLAB programming: Fundamentals

Introduction to MATLAB programming: Fundamentals Introduction to MATLAB programming: Fundamentals Shan He School for Computational Science University of Birmingham Module 06-23836: Computational Modelling with MATLAB Outline Outline of Topics Why MATLAB?

More information

A General Introduction to Matlab

A General Introduction to Matlab Master Degree Course in ELECTRONICS ENGINEERING http://www.dii.unimore.it/~lbiagiotti/systemscontroltheory.html A General Introduction to Matlab e-mail: luigi.biagiotti@unimore.it http://www.dii.unimore.it/~lbiagiotti

More information

MATLAB = MATrix LABoratory. Interactive system. Basic data element is an array that does not require dimensioning.

MATLAB = MATrix LABoratory. Interactive system. Basic data element is an array that does not require dimensioning. Introduction MATLAB = MATrix LABoratory Interactive system. Basic data element is an array that does not require dimensioning. Efficient computation of matrix and vector formulations (in terms of writing

More information

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An. CSE 10 Interacting with MATLAB Instructor: Aijun An Department of Computer Science and Engineering York University aan@cse.yorku.ca Outline Starting MATLAB MATLAB Windows Using the Command Window Some

More information

Experiment 1: Introduction to MATLAB I. Introduction. 1.1 Objectives and Expectations: 1.2 What is MATLAB?

Experiment 1: Introduction to MATLAB I. Introduction. 1.1 Objectives and Expectations: 1.2 What is MATLAB? Experiment 1: Introduction to MATLAB I Introduction MATLAB, which stands for Matrix Laboratory, is a very powerful program for performing numerical and symbolic calculations, and is widely used in science

More information

10 M-File Programming

10 M-File Programming MATLAB Programming: A Quick Start Files that contain MATLAB language code are called M-files. M-files can be functions that accept arguments and produce output, or they can be scripts that execute a series

More information

A Guide to Using Some Basic MATLAB Functions

A Guide to Using Some Basic MATLAB Functions A Guide to Using Some Basic MATLAB Functions UNC Charlotte Robert W. Cox This document provides a brief overview of some of the essential MATLAB functionality. More thorough descriptions are available

More information

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX 1) Objective The objective of this lab is to review how to access Matlab, Simulink, and the Communications Toolbox, and to become familiar

More information

To start using Matlab, you only need be concerned with the command window for now.

To start using Matlab, you only need be concerned with the command window for now. Getting Started Current folder window Atop the current folder window, you can see the address field which tells you where you are currently located. In programming, think of it as your current directory,

More information

LAB 1 General MATLAB Information 1

LAB 1 General MATLAB Information 1 LAB 1 General MATLAB Information 1 General: To enter a matrix: > type the entries between square brackets, [...] > enter it by rows with elements separated by a space or comma > rows are terminated by

More information

Matlab Tutorial and Exercises for COMP61021

Matlab Tutorial and Exercises for COMP61021 Matlab Tutorial and Exercises for COMP61021 1 Introduction This is a brief Matlab tutorial for students who have not used Matlab in their programming. Matlab programming is essential in COMP61021 as a

More information

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix. MATLAB Tutorial 1 1 Department of Mathematics and Statistics, The University of New Mexico, Albuquerque, NM 87131 August 28, 2016 Contents: 1. Scalars, Vectors, Matrices... 1 2. Built-in variables, functions,

More information

MATLAB BASICS. M Files. Objectives

MATLAB BASICS. M Files. Objectives Objectives MATLAB BASICS 1. What is MATLAB and why has it been selected to be the tool of choice for DIP? 2. What programming environment does MATLAB offer? 3. What are M-files? 4. What is the difference

More information

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices Introduction to Interactive Calculations Matlab is interactive, no need to declare variables >> 2+3*4/2 >> V = 50 >> V + 2 >> V Ans = 52 >> a=5e-3; b=1; a+b Most elementary functions and constants are

More information

Introduction to Scientific Computing with Matlab

Introduction to Scientific Computing with Matlab UNIVERSITY OF WATERLOO Introduction to Scientific Computing with Matlab SAW Training Course R. William Lewis Computing Consultant Client Services Information Systems & Technology 2007 Table of Contents

More information

Laboratory 1 Octave Tutorial

Laboratory 1 Octave Tutorial Signals, Spectra and Signal Processing Laboratory 1 Octave Tutorial 1.1 Introduction The purpose of this lab 1 is to become familiar with the GNU Octave 2 software environment. 1.2 Octave Review All laboratory

More information

Dr Richard Greenaway

Dr Richard Greenaway SCHOOL OF PHYSICS, ASTRONOMY & MATHEMATICS 4PAM1008 MATLAB 3 Creating, Organising & Processing Data Dr Richard Greenaway 3 Creating, Organising & Processing Data In this Workshop the matrix type is introduced

More information

Lecture 2: Variables, Vectors and Matrices in MATLAB

Lecture 2: Variables, Vectors and Matrices in MATLAB Lecture 2: Variables, Vectors and Matrices in MATLAB Dr. Mohammed Hawa Electrical Engineering Department University of Jordan EE201: Computer Applications. See Textbook Chapter 1 and Chapter 2. Variables

More information

Welcome to EGR 106 Foundations of Engineering II

Welcome to EGR 106 Foundations of Engineering II Welcome to EGR 106 Foundations of Engineering II Course information Today s specific topics: Computation and algorithms MATLAB Basics Demonstrations Material in textbook chapter 1 Computation What is computation?

More information

Programming in Mathematics. Mili I. Shah

Programming in Mathematics. Mili I. Shah Programming in Mathematics Mili I. Shah Starting Matlab Go to http://www.loyola.edu/moresoftware/ and login with your Loyola name and password... Matlab has eight main windows: Command Window Figure Window

More information

Introduction to MATLAB

Introduction to MATLAB 58:110 Computer-Aided Engineering Spring 2005 Introduction to MATLAB Department of Mechanical and industrial engineering January 2005 Topics Introduction Running MATLAB and MATLAB Environment Getting help

More information

Dr Richard Greenaway

Dr Richard Greenaway SCHOOL OF PHYSICS, ASTRONOMY & MATHEMATICS 4PAM1008 MATLAB 2 Basic MATLAB Operation Dr Richard Greenaway 2 Basic MATLAB Operation 2.1 Overview 2.1.1 The Command Line In this Workshop you will learn how

More information

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB? Appendix A Introduction to MATLAB A.1 What Is MATLAB? MATLAB is a technical computing environment developed by The Math- Works, Inc. for computation and data visualization. It is both an interactive system

More information

Digital Image Analysis and Processing CPE

Digital Image Analysis and Processing CPE Digital Image Analysis and Processing CPE 0907544 Matlab Tutorial Dr. Iyad Jafar Outline Matlab Environment Matlab as Calculator Common Mathematical Functions Defining Vectors and Arrays Addressing Vectors

More information

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window. EE 350L: Signals and Transforms Lab Spring 2007 Lab #1 - Introduction to MATLAB Lab Handout Matlab Software: Matlab will be the analytical tool used in the signals lab. The laboratory has network licenses

More information

Quick MATLAB Syntax Guide

Quick MATLAB Syntax Guide Quick MATLAB Syntax Guide Some useful things, not everything if-statement Structure: if (a = = = ~=

More information

Lab of COMP 406. MATLAB: Quick Start. Lab tutor : Gene Yu Zhao Mailbox: or Lab 1: 11th Sep, 2013

Lab of COMP 406. MATLAB: Quick Start. Lab tutor : Gene Yu Zhao Mailbox: or Lab 1: 11th Sep, 2013 Lab of COMP 406 MATLAB: Quick Start Lab tutor : Gene Yu Zhao Mailbox: csyuzhao@comp.polyu.edu.hk or genexinvivian@gmail.com Lab 1: 11th Sep, 2013 1 Where is Matlab? Find the Matlab under the folder 1.

More information

PowerPoints organized by Dr. Michael R. Gustafson II, Duke University

PowerPoints organized by Dr. Michael R. Gustafson II, Duke University Part 1 Chapter 2 MATLAB Fundamentals PowerPoints organized by Dr. Michael R. Gustafson II, Duke University All images copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

More information

Matlab Programming Introduction 1 2

Matlab Programming Introduction 1 2 Matlab Programming Introduction 1 2 Mili I. Shah August 10, 2009 1 Matlab, An Introduction with Applications, 2 nd ed. by Amos Gilat 2 Matlab Guide, 2 nd ed. by D. J. Higham and N. J. Higham Starting Matlab

More information

Lecture 1: What is MATLAB?

Lecture 1: What is MATLAB? Lecture 1: What is MATLAB? Dr. Mohammed Hawa Electrical Engineering Department University of Jordan EE201: Computer Applications. See Textbook Chapter 1. MATLAB MATLAB (MATrix LABoratory) is a numerical

More information

Matlab Tutorial for COMP24111 (includes exercise 1)

Matlab Tutorial for COMP24111 (includes exercise 1) Matlab Tutorial for COMP24111 (includes exercise 1) 1 Exercises to be completed by end of lab There are a total of 11 exercises through this tutorial. By the end of the lab, you should have completed the

More information

Introduction to MATLAB

Introduction to MATLAB Chapter 1 Introduction to MATLAB 1.1 Software Philosophy Matrix-based numeric computation MATrix LABoratory built-in support for standard matrix and vector operations High-level programming language Programming

More information

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks MATLAB Basics Stanley Liang, PhD York University Configure a MATLAB Package Get a MATLAB Student License on Matworks Visit MathWorks at https://www.mathworks.com/ It is recommended signing up with a student

More information

What is MATLAB? It is a high-level programming language. for numerical computations for symbolic computations for scientific visualizations

What is MATLAB? It is a high-level programming language. for numerical computations for symbolic computations for scientific visualizations What is MATLAB? It stands for MATrix LABoratory It is developed by The Mathworks, Inc (http://www.mathworks.com) It is an interactive, integrated, environment for numerical computations for symbolic computations

More information

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment

What is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment What is MATLAB? MATLAB PROGRAMMING Stands for MATrix LABoratory A software built around vectors and matrices A great tool for numerical computation of mathematical problems, such as Calculus Has powerful

More information

MATLAB Tutorial. 1. The MATLAB Windows. 2. The Command Windows. 3. Simple scalar or number operations

MATLAB Tutorial. 1. The MATLAB Windows. 2. The Command Windows. 3. Simple scalar or number operations MATLAB Tutorial The following tutorial has been compiled from several resources including the online Help menu of MATLAB. It contains a list of commands that will be directly helpful for understanding

More information

ELEN E3084: Signals and Systems Lab Lab II: Introduction to Matlab (Part II) and Elementary Signals

ELEN E3084: Signals and Systems Lab Lab II: Introduction to Matlab (Part II) and Elementary Signals ELEN E384: Signals and Systems Lab Lab II: Introduction to Matlab (Part II) and Elementary Signals 1 Introduction In the last lab you learn the basics of MATLAB, and had a brief introduction on how vectors

More information

DSP Laboratory (EELE 4110) Lab#1 Introduction to Matlab

DSP Laboratory (EELE 4110) Lab#1 Introduction to Matlab Islamic University of Gaza Faculty of Engineering Electrical Engineering Department 2012 DSP Laboratory (EELE 4110) Lab#1 Introduction to Matlab Goals for this Lab Assignment: In this lab we would have

More information

QUICK INTRODUCTION TO MATLAB PART I

QUICK INTRODUCTION TO MATLAB PART I QUICK INTRODUCTION TO MATLAB PART I Department of Mathematics University of Colorado at Colorado Springs General Remarks This worksheet is designed for use with MATLAB version 6.5 or later. Once you have

More information

How to Use MATLAB. What is MATLAB. Getting Started. Online Help. General Purpose Commands

How to Use MATLAB. What is MATLAB. Getting Started. Online Help. General Purpose Commands How to Use MATLAB What is MATLAB MATLAB is an interactive package for numerical analysis, matrix computation, control system design and linear system analysis and design. On the server bass, MATLAB version

More information

Logical Subscripting: This kind of subscripting can be done in one step by specifying the logical operation as the subscripting expression.

Logical Subscripting: This kind of subscripting can be done in one step by specifying the logical operation as the subscripting expression. What is the answer? >> Logical Subscripting: This kind of subscripting can be done in one step by specifying the logical operation as the subscripting expression. The finite(x)is true for all finite numerical

More information

INTRODUCTION TO MATLAB PLOTTING WITH MATLAB

INTRODUCTION TO MATLAB PLOTTING WITH MATLAB 1 INTRODUCTION TO MATLAB PLOTTING WITH MATLAB Plotting with MATLAB x-y plot Plotting with MATLAB MATLAB contains many powerful functions for easily creating plots of several different types. Command plot(x,y)

More information

This is a basic tutorial for the MATLAB program which is a high-performance language for technical computing for platforms:

This is a basic tutorial for the MATLAB program which is a high-performance language for technical computing for platforms: Appendix A Basic MATLAB Tutorial Extracted from: http://www1.gantep.edu.tr/ bingul/ep375 http://www.mathworks.com/products/matlab A.1 Introduction This is a basic tutorial for the MATLAB program which

More information

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis Introduction to Matlab 1 Outline What is Matlab? Matlab desktop & interface Scalar variables Vectors and matrices Exercise 1 Booleans Control structures File organization User defined functions Exercise

More information

Starting Matlab. MATLAB Laboratory 09/09/10 Lecture. Command Window. Drives/Directories. Go to.

Starting Matlab. MATLAB Laboratory 09/09/10 Lecture. Command Window. Drives/Directories. Go to. Starting Matlab Go to MATLAB Laboratory 09/09/10 Lecture Lisa A. Oberbroeckling Loyola University Maryland loberbroeckling@loyola.edu http://ctx.loyola.edu and login with your Loyola name and password...

More information

CITS2401 Computer Analysis & Visualisation

CITS2401 Computer Analysis & Visualisation FACULTY OF ENGINEERING, COMPUTING AND MATHEMATICS CITS2401 Computer Analysis & Visualisation SCHOOL OF COMPUTER SCIENCE AND SOFTWARE ENGINEERING Topic 3 Introduction to Matlab Material from MATLAB for

More information

Computer Programming in MATLAB

Computer Programming in MATLAB Computer Programming in MATLAB Prof. Dr. İrfan KAYMAZ Atatürk University Engineering Faculty Department of Mechanical Engineering What is a computer??? Computer is a device that computes, especially a

More information

Matlab Tutorial. The value assigned to a variable can be checked by simply typing in the variable name:

Matlab Tutorial. The value assigned to a variable can be checked by simply typing in the variable name: 1 Matlab Tutorial 1- What is Matlab? Matlab is a powerful tool for almost any kind of mathematical application. It enables one to develop programs with a high degree of functionality. The user can write

More information

MATLAB COURSE FALL 2004 SESSION 1 GETTING STARTED. Christian Daude 1

MATLAB COURSE FALL 2004 SESSION 1 GETTING STARTED. Christian Daude 1 MATLAB COURSE FALL 2004 SESSION 1 GETTING STARTED Christian Daude 1 Introduction MATLAB is a software package designed to handle a broad range of mathematical needs one may encounter when doing scientific

More information

Introduction to MATLAB

Introduction to MATLAB Introduction to MATLAB Introduction MATLAB is an interactive package for numerical analysis, matrix computation, control system design, and linear system analysis and design available on most CAEN platforms

More information

Introduction to Matlab. By: Hossein Hamooni Fall 2014

Introduction to Matlab. By: Hossein Hamooni Fall 2014 Introduction to Matlab By: Hossein Hamooni Fall 2014 Why Matlab? Data analytics task Large data processing Multi-platform, Multi Format data importing Graphing Modeling Lots of built-in functions for rapid

More information

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah)

ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah) Introduction ELEC4042 Signal Processing 2 MATLAB Review (prepared by A/Prof Ambikairajah) MATLAB is a powerful mathematical language that is used in most engineering companies today. Its strength lies

More information

Matlab Introduction. Scalar Variables and Arithmetic Operators

Matlab Introduction. Scalar Variables and Arithmetic Operators Matlab Introduction Matlab is both a powerful computational environment and a programming language that easily handles matrix and complex arithmetic. It is a large software package that has many advanced

More information

AN INTRODUCTION TO MATLAB

AN INTRODUCTION TO MATLAB AN INTRODUCTION TO MATLAB 1 Introduction MATLAB is a powerful mathematical tool used for a number of engineering applications such as communication engineering, digital signal processing, control engineering,

More information

Introduction to MATLAB LAB 1

Introduction to MATLAB LAB 1 Introduction to MATLAB LAB 1 1 Basics of MATLAB MATrix LABoratory A super-powerful graphing calculator Matrix based numeric computation Embedded Functions Also a programming language User defined functions

More information

Chapter 2. MATLAB Fundamentals

Chapter 2. MATLAB Fundamentals Chapter 2. MATLAB Fundamentals Choi Hae Jin Chapter Objectives q Learning how real and complex numbers are assigned to variables. q Learning how vectors and matrices are assigned values using simple assignment,

More information

MATLAB Fundamentals. Berlin Chen Department of Computer Science & Information Engineering National Taiwan Normal University

MATLAB Fundamentals. Berlin Chen Department of Computer Science & Information Engineering National Taiwan Normal University MATLAB Fundamentals Berlin Chen Department of Computer Science & Information Engineering National Taiwan Normal University Reference: 1. Applied Numerical Methods with MATLAB for Engineers, Chapter 2 &

More information

GUI Alternatives. Syntax. Description. MATLAB Function Reference plot. 2-D line plot

GUI Alternatives. Syntax. Description. MATLAB Function Reference plot. 2-D line plot MATLAB Function Reference plot 2-D line plot GUI Alternatives Use the Plot Selector to graph selected variables in the Workspace Browser and the Plot Catalog, accessed from the Figure Palette. Directly

More information

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY

MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY MATLAB Basics EE107: COMMUNICATION SYSTEMS HUSSAIN ELKOTBY What is MATLAB? MATLAB (MATrix LABoratory) developed by The Mathworks, Inc. (http://www.mathworks.com) Key Features: High-level language for numerical

More information

MATLAB is a multi-paradigm numerical computing environment fourth-generation programming language. A proprietary programming language developed by

MATLAB is a multi-paradigm numerical computing environment fourth-generation programming language. A proprietary programming language developed by 1 MATLAB is a multi-paradigm numerical computing environment fourth-generation programming language. A proprietary programming language developed by MathWorks In 2004, MATLAB had around one million users

More information

AMS 27L LAB #1 Winter 2009

AMS 27L LAB #1 Winter 2009 AMS 27L LAB #1 Winter 2009 Introduction to MATLAB Objectives: 1. To introduce the use of the MATLAB software package 2. To learn elementary mathematics in MATLAB Getting Started: Log onto your machine

More information

Computational Modelling 102 (Scientific Programming) Tutorials

Computational Modelling 102 (Scientific Programming) Tutorials COMO 102 : Scientific Programming, Tutorials 2003 1 Computational Modelling 102 (Scientific Programming) Tutorials Dr J. D. Enlow Last modified August 18, 2003. Contents Tutorial 1 : Introduction 3 Tutorial

More information

A very brief Matlab introduction

A very brief Matlab introduction A very brief Matlab introduction Siniša Krajnović January 24, 2006 This is a very brief introduction to Matlab and its purpose is only to introduce students of the CFD course into Matlab. After reading

More information

Inlichtingenblad, matlab- en simulink handleiding en practicumopgaven IWS

Inlichtingenblad, matlab- en simulink handleiding en practicumopgaven IWS Inlichtingenblad, matlab- en simulink handleiding en practicumopgaven IWS 1 6 3 Matlab 3.1 Fundamentals Matlab. The name Matlab stands for matrix laboratory. Main principle. Matlab works with rectangular

More information

MATLAB Project: Getting Started with MATLAB

MATLAB Project: Getting Started with MATLAB Name Purpose: To learn to create matrices and use various MATLAB commands for reference later MATLAB functions used: [ ] : ; + - * ^, size, help, format, eye, zeros, ones, diag, rand, round, cos, sin,

More information

Objectives. 1 Running, and Interface Layout. 2 Toolboxes, Documentation and Tutorials. 3 Basic Calculations. PS 12a Laboratory 1 Spring 2014

Objectives. 1 Running, and Interface Layout. 2 Toolboxes, Documentation and Tutorials. 3 Basic Calculations. PS 12a Laboratory 1 Spring 2014 PS 12a Laboratory 1 Spring 2014 Objectives This session is a tutorial designed to a very quick overview of some of the numerical skills that you ll need to get started. Throughout the tutorial, the instructors

More information

Stokes Modelling Workshop

Stokes Modelling Workshop Stokes Modelling Workshop 14/06/2016 Introduction to Matlab www.maths.nuigalway.ie/modellingworkshop16/files 14/06/2016 Stokes Modelling Workshop Introduction to Matlab 1 / 16 Matlab As part of this crash

More information

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group

Introduction to MATLAB. Simon O Keefe Non-Standard Computation Group Introduction to MATLAB Simon O Keefe Non-Standard Computation Group sok@cs.york.ac.uk Content n An introduction to MATLAB n The MATLAB interfaces n Variables, vectors and matrices n Using operators n Using

More information