Introduction to MATLAB
|
|
- Lynne Jenkins
- 5 years ago
- Views:
Transcription
1 GENG 200 Introduction to Programming Faculty of Engineering, ERU
2 Table of Contents 1. Getting Started with MATLAB Introduction Graphical User Interface Help Menu Basic Data Manipulation Simple variables and data assignments Scripts (M-Files) Vectors Creating Vectors Operations on Vectors Arithmetic Operations Logical Operations Applying Library Functions MATLAB Arrays (Matrices) Creating an Array Operations on Arrays Arithmetic Operations Applying Library Functions Execution Control Relational and Logical Operators if Statements while Loop for Loop User Defined Functions D Plots Basic 2-D Plots Subplots UAE University, Faculty of Engineering, ERU Ayman Rabee 2
3 1.1 Introduction 1. Getting Started with MATLAB MATLAB, which stands for MATrix LABoratory, is a state-of-the-art mathematical software package, which is used extensively in both academia and industry. It is highlevel technical computing language and interactive environment for algorithm development, data visualization, data analysis, and numeric computation. As one can guess from its name, MATLAB deals mainly with matrices. A scalar is a 1- by-1 matrix and a row vector of length say 10, is a 1-by-10 matrix. We will elaborate more on these and other features of MATLAB in the sections that follow. 1.2 Graphical User Interface MATLAB uses several display windows (see Figure 1.1). The default view includes command window, current directory, workspace, and command history windows. Command Window Current Directory Workspace Window Command History Figure 1.1 MATLAB Default Window Configuration UAE University, Faculty of Engineering, ERU Ayman Rabee 3
4 Command Window: This window offers an environment similar to scientific calculator, which will help you in performing fast experiments of your commands and finds out the results of fragments of your code. Command History: This window will save a record of your commands you issued in the command window. Workspace Window: This window will show the variables you have defined, and it will keep track of them. When you open MATLAB every time this window will be empty because you aren t defining any variables yet. Current Directory: MATLAB accesses files and saves information to a location on your hard drive given by the current directory. 1.3 Help Menu The MATLAB help menu is very powerful. It contains detailed description of every command used in MATLAB along with illustrative examples to show the user the explanation of the command and how it can be used. To access the help menu, from the help tab select Product Help. Then you can search for any command to get detailed information. See Figure 1.2 which shows the details of the sin function. Type the phrase you want to search for Figure 1.2 The Help Menu 1 UAE University, Faculty of Engineering, ERU Ayman Rabee 4
5 1.4 Basic Data Manipulation Simple variables and data assignments MATLAB presents very easy environment for defining simple variables. Remember that any simple variable (scalar) is considered as a 1-by-1 matrix. Now, if you want to define a variable in MATLAB just go directly to the command window where you will see the prompt (>>) and type the variable name and assign a numerical value and press Enter button. When your command is executed, the MATLAB will respond by showing you the result of calculation. Note 1: If you are doing calculation without assigning the output to a variable (see example 1.1), the output will be assigned to a variable called ans created by MATLAB itself. Note 2: MATLAB is case sensitive. That is: x + y is not the same as X + y The command window can be used to type and execute all MATLAB commands. Also it can be used as a scientific calculator to perform simple and complex operations. Example 1.1: Calculate: 5*2*(6 4 +2). Type in the numbers and hit Enter >> 5*2*(6^4+2) Example 1.2: Calculate: x*y+3; where x = 3, y = 4 >> x = 3 x = 3 >> y = 4 y = 4 >> x*y+3 15 After doing the previous examples, look at the workspace window. You will see the variables and results there as shown in Figure 1.3. Note 3: The following commands are useful clc: clears the command window clear: removes the variables from the workspace UAE University, Faculty of Engineering, ERU Ayman Rabee 5
6 Figure 1.3 Variables added in the Workspace Example 1.3: Calculate the volume of a cylinder if height = 10 cm, radius = 5 cm using: v = height*π*radius 2 >> h = 10 % height h = 10 >> r = 5 % radius r = 5 >> v = h*pi*r^2 % volume v = In the previous example, as you can see that the symbol (%) is used for documentation and the constant π is defined in MATLAB as pi Scripts (M-Files) MATLAB uses text files for saving scripts (set of instructions) and executing them rather than just entering the commands in the command window. It uses its own editor to create those text files with the extension.m, and referred to as m-files. You can create m-file by choosing: File>New>M-File (or by clicking on the new icon on the far left of the MATLAB s toolbar). Once you created your m-file, you need to save it so that you can run and refer to it in future. However, in order to run the m-file it should be in the current directory of the MATLAB. Let us redo example 1.3 but this time using m-file. Create a new m-file (by selecting File>New>M-File) and fill in the commands as shown in Figure 1.4. Save the m-file as volume.m To execute the volume.m, press F5 or from debug menu select run or from toolbar of the m-file press on the green play button (or you can write the name of the m-file on the command line and press Enter key, so in this example: >>volume). UAE University, Faculty of Engineering, ERU Ayman Rabee 6
7 To Run Remove the semicolon to display the value of v on the command window Figure 1.4 M-File for calculating the volume of a cylinder Note 4: Terminate any line with semicolon (;) to suppress the output Example 1.5: Write m-file to calculate the roots of the quadratic equation: f(x) = a*x 2 + b*x + c; where: a, b, and c are constants and a 0. % This m-file to calculate the roots of any quadratic % equation of the form % f(x) = a*x^2 + b*x + c % Use the discriminant to find x1 and x2 clear clc % Define the coeff: a, b and c a = 2; b = 4; c = 1; % Calculate the Roots: x1, x2 x1 = (-b - sqrt(b^2-4*a*c))/(2*a) x2 = (-b + sqrt(b^2-4*a*c))/(2*a) When you run the m-file. The roots calculated will be: x1 = X2 = UAE University, Faculty of Engineering, ERU Ayman Rabee 7
8 2. Vectors 2.1 Creating Vectors A vector is one-dimensional matrix (array) as shown in Figure 2.1 which contains data items such as: numbers. Individual items in a vector are usually referred to as elements. Vector elements have two properties: their numerical values and position (index) making them unique in a specific vector. Value: Index: n-1 n Figure 2.1 A vector There are many different ways to create a vector. The following shows how to create a vector: Entering the values directly variable_name = [type vectors elements here] For example: a = [2, 4, 6, 8]. The commas are optional and can be omitted, that is you can write: a = [ ]. Creating a vector with constant spacing by using colon operator (:) variable_name = [first element: spacing : Last element] For example: x = [1:2:10]. Note that the brackets are optional and the spacing can be omitted if the increment you need is 1. Using the linspace( ) function to create a fixed number of values between two limits. variable_name = linspace(x i, x f, n). Where x i : initial limit, x f : final limit and n: number of numbers of values in the vector. For example: x = linspace(0,10,6) Using built-in function such as: ones(1,n),zeros(1,n), and rand(1,n). We will discuss the use of these functions in the following examples. Example 2.1: Entering values directly >> x = [ ] x = >> a = [4, 10, 12, 20] a = UAE University, Faculty of Engineering, ERU Ayman Rabee 8
9 Example 2.2: Using the colon operator >> m = [0:2:10] % vector of 1-by-6 m = >> w = 1:2:10 % vector of 1-by-5 w = Example 2.3: Using linespace( ) function >> x = linspace(0,10,6) x = >> y = [linspace(0,10,3)] y = >> z = [linspace(0,10,4)] z = >> cd=6;e=3;h=4; Three variables are defined >> arr = [e cd*h cos(pi/3) h^2 sqrt(h*h/cd) 14] arr = Elements are defined using mathematical expressions Example 2.4: Creating vectors using zeros, ones and rand functions % rand(1,n) create a 1-by-n vector of random numbers % between 0 and 1 % Ones(1,n) create a 1-by-n vector of ones % zeros(1,n) create a 1-by-n vector of zeros >> a=rand(1,4) a = >> b=ones(1,4) b = >> c=zeros(1,4) c = UAE University, Faculty of Engineering, ERU Ayman Rabee 9
10 Sometimes there is a need to generate random numbers that are distributed in an interval other than (0, 1), or to have numbers that are only integers. Random numbers that distributed in a range (a, b) can be obtained by the following equation (1-by-n vector of random numbers between a and b): variable_name = (b-a)*rand(1,n)+a Example 2.5: Generate a 1-by-5 vector random numbers between 0 and 10 >> a=0;b=10; >> x = (b-a)*rand(1,5)+a x = Random numbers that are all integers can be generated using rand( ) with round( ) function. See the following example. Example 2.6: Generate a 1-by-10 vector of integer random numbers from 1 to 100 >> a=1;b=100; >> x = round((b-a)*rand(1,10)+a) x = Indexing and Accessing a Vector The elements of a vector can be accessed by enclosing the index of the required elements in parenthesis. For example: X(3) would return the third element. If you attempt to read beyond the length of the vector or below index 1, an error will result. Example 2.7: >> A = [ ] A = >> A(1) 3 >> A(5) 0 >> A(0) numel(a) returns number of elements in array. An equivalent command, for vectors, is length(a)??? Attempted to access A(0); index must be a positive integer or logical. >> A(7)??? Attempted to access A(7); index out of bounds because numel(a)=6. UAE University, Faculty of Engineering, ERU Ayman Rabee 10
11 Note that you can change the value of any element in a vector. In general, you can use: A(index) = new_value We can also access elements of a vector using the colon operator (:). For example: A(:) refers to all elements of the vector A, and A(m:n) refers to elements m through n, n>m. 2.2 Operations on Vectors Arithmetic Operations Since all variables in MATLAB are considered as arrays (scalar:1 1, vector: 1 n, array: n n), one should take care of how to perform: multiplication, division and exponentiation. On the other hand addition and subtraction have the syntax exactly as one would expect. The first set of operations with vectors is element-by-element operations, not array operations, and hence, linear algebra rules do not apply in this case. Therefore, new set of symbols is required. For multiplication we will use (.*), for division we will use (./) and for exponentiation we will use (.^). Note that the new set is using the dot to represent that the operation is element-by-element operation. Consider the following examples. Note 5: vector by vector operation requires that both vectors should be of the same length. That is, they have the same number of elements. Example 2.8: >> A = [ ] A = >> B = [ ] B = >> A >> A.* >> A*B??? Error using ==> mtimes Inner matrix dimensions must agree. >> A.*B >> A^2??? Error using ==> mpower UAE University, Faculty of Engineering, ERU Ayman Rabee 11
12 Matrix must be square. >> A.^ >> A*A??? Error using ==> mtimes Inner matrix dimensions must agree. >> A.*A Logical Operations We can perform logical operations using relational operators (we will discuss logical operators in the coming sections) listed in table 2.1. Those operations can produce numerical or logical results. Table 2.1 Relational Operators in MATLAB Operator Description < Less than <= Less than or equal to > Greater than >= Greater than or equal to == Equal to ~= Not equal to As with arithmetic operations, logical operations can be carried out element-by-element on two vectors as long as both vectors are of the same length. Consider example 2.9. Example 2.9: >> A = [ ] A = >> B = [ ] B = >> A >= 5 Return where A is greater than or equal to >> A(A >= 5) Return elements that are greater than or equal to 5 UAE University, Faculty of Engineering, ERU Ayman Rabee 12
13 Return where each element of A that is not less >> A>=B than the corresponding elements of B Note 6: An alternative to using indexing into the vector using the logical expression is to use the find function. For example: find(a>=5) will return where A is greater than or equal to Applying Library Functions MATLAB provides rich collection of mathematical functions that cover mathematical, trigonometric, and statistical operations. For the partial list of functions go to the command window and type the following help commands: >>help elfun %List of elementary mathematical functions >>help specfun %List of specialized math functions >>help elmat %List of elementary matrices functions We will explain the following functions because they provide specific capabilities that are frequently used. sum(a) and mean(a) calculate the sum and mean of the vector A respectively. min(a) and max(a) return two outputs, the minimum or maximum value in a vector and the position (index) where that value occurred. Example 2.10: >> A = [ ] A = >> sum(a) 26 >> mean(a) >> [max i] = max(a) max = 10 i = 7 >> [min i] = min(a) min = -1 i = 1 UAE University, Faculty of Engineering, ERU Ayman Rabee 13
14 Example 2.11: Voltage Divider When several resistors are connected in an electrical circuit in series, the voltage across each resistor is given by: Where V n and R n are the voltage across resistor n and its resistance, respectively. R eq = sum of all resistors, is the equivalent resistance, and V s is the source voltage. The power dissipated in each in each resistor is given by: The figure below shows a circuit with seven resistors connected in series. Write a MATLAB program in m-file that calculates voltage across each resistor and the power dissipated in each resistor. Also calculate total power dissipated in all resistors and the current that flows in circuit using Ohm law: current = V s /R eq. Consider the following values: Vs = 24 V, R1 = 20Ω, R2 = 14 Ω, R3 = 12Ω, R4 = 18Ω, R5 = 8Ω, R6 = 15Ω, R7 = 7Ω. Solution: The following m-file is also shown in figure 2.1 clear;clc % Define values of the voltage source and all resistors. Vs=24; R1=20;R2=14;R3=12; R4=18;R5=8;R6=15;R7=10; % Define a vector Rn Rn = [R1 R2 R3 R4 R5 R6 R7]; % Calculate the equivalent resistor Req = sum(rn); % Apply the Volatge Divider Rule Vn = Rn*Vs/Req % Calculate the power in each resistor Pn = Rn*Vs^2/Req^2 % Calculate the current using ohm law I = V/R I = Vs/Req % Calculate the total power totalpower = sum(pn) UAE University, Faculty of Engineering, ERU Ayman Rabee 14
15 The command window where the m-file was executed: Vn = Pn = I = totalpower = To Run Figure 2.1 M-file of voltage divider (example 2.11) UAE University, Faculty of Engineering, ERU Ayman Rabee 15
16 3. MATLAB Arrays (Matrices) In the previous section we saw that vector is a simple way to group a collection of similar data items. Let us now extend the idea to include arrays confined to two dimensional arrays. Figure 2.2 shows a typical two dimensional array A with m rows and n columns and A a transpose array of A with n rows and m columns. A transposed array is obtained by interchanging the values of in rows and columns. To transpose an array in MATLAB you can use the apostrophe character ( ) placed after the array: A_tarnspose = A. Note that you can obtain a transpose of a vector in the same way. [ ] [ ] Figure 2.2 An Array and Its Transpose 3.1 Creating an Array As with vectors, you can create arrays in MATLAB using many different ways. The following summaries most common techniques: You can enter the values directly using semicolon to indicate the end of a row. For example: A = [2 4 6; 1 3 5], A is 2 x 3 array. The functions zeros(m, n) and ones(m, n) create creates arrays with m rows and n columns filled with zeros and ones respectively. The function rand(m, n) create an array filled with random numbers in the range from 0 to 1. The function diag(a) where A an array, returns its diagonal as a column vector, and diag(b) where B is a vector, returns a square array of zeros and its diagonal is that vector B. The function magic(m), which creates a square array of size m x m filled with numbers from 1 to m 2 organized in such a way that its rows, columns, and diagonals all add up to the same value. UAE University, Faculty of Engineering, ERU Ayman Rabee 16
17 Example 3.1: >> A = [2 4 6; ] A = >> A = [2 4; 6 8] A = >> B=zeros(3,3) B = >> C = [ones(2,2) zeros(2,2)] C = >> rand(3,4) Example 3.2: >> A = [2 3 4; 7 8 9] A = >> diag(a) 2 8 To access a specific element in an 2D array, just indicate the row and column of the specified element, i.e., A(row,col). Also the colon operator can be used to access array elements. The following notations illustrate some of the different cases: A(:,n) Refers to all elements in all rows of a column n of the array A. A(n,:) Refers to all elements in all columns of a row n of the array A. A(:,m:n) Refers to all elements in all rows between columns m and n of the array A. 3.2 Operations on Arrays In this section we are going to discuss operations performed on arrays involving the basic arithmetic operations, library functions and built-in functions. UAE University, Faculty of Engineering, ERU Ayman Rabee 17
18 However, arithmetic operations can be done in two ways. One way, which uses standard symbols (*, /, and ^), follows the rules of linear algebra. The second way, which is called element-by-element operations (.*,./, and.^). In addition, in both types of calculations, MATLAB has left division (\ or.\) which are explained later Arithmetic Operations Addition and Subtraction: Standard addition or subtraction can be done on arrays of identical size (the same number of rows and columns). Also can be done when we want to add (subtract) a scalar value to an array. When two arrays are involved, the sum (or difference) is performed by adding (or subtracting) their corresponding elements. But when a scalar (number) is involved, that number is added (or subtracted from) all the elements of the array. Consider the following examples. Example 3.3: >> A = [2 4 1; 3 9 5] A = >> B = [1 2 3; 4 5 6] B = >> A - B >> A + B >> A >> B UAE University, Faculty of Engineering, ERU Ayman Rabee 18
19 Multiplication: The multiplication * of arrays is executed by MATLAB according to the rules of linear algebra (This is known as matrix multiplication). This means that if A*B is to be executed. Then the number of columns in matrix A should equal to the number of rows in matrix B. The result is a matrix that has the same number of rows as A and the same number of columns as B. For example: if A 4x3 *B 3x2 will result in a new matrix C 4x2. This means that A*B B*A. C 4x2 = A 4x3 *B 3x2 Consider the following example. Example 3.4: >> A=[1 2 3; 4 5 6;7 8 9] %3x3 A = >> B=[2 3 ;-4 7;5 5]%2x3 B = >> A*B >> B*A??? Error using ==> mtimes Inner matrix dimensions must agree. Division: MATLAB has two types of array division. Which are right division ( / ) and left division ( \ ). But before we can start with these operations let us define two terms: Identity Matrix and Inverse of a matrix. Identity Matrix is a square matrix in which the diagonal elements are 1 s and the rest of the elements are 0 s. When the identity matrix multiplies another matrix (multiplication should be done according to linear algebra), that matrix is unchanged. That is: A*I = I*A=A. The identity matrix can be generated in MATLAB using eye(n) which will create n x n identity matrix. UAE University, Faculty of Engineering, ERU Ayman Rabee 19
20 Inverse of a matrix is best explained using the following illustration. The matrix B is the inverse of matrix A if when the two matrices are multiplied, their product is the identity matrix. Both matrices must be square and the order can be A*B or B*A. The inverse of matrix A can be written as A -1. In MATLAB you can find the inverse using the two commands: inv(a) or raise to the power of -1, that is: A^-1. The following example illustrates both identity and inverse matrices. Example 3.5: Inverse and Identity Matrices >> A=[2 1 4;4 1 8;2-1 3] %Create the Matrix A = >> B=inv(A) %use inv() to find the inverse of A B = >> A*B %multiplication of A and B gives the Identity Matrix >> A^-1 % use power of -1 to find the inverse of A >> B-A^ Right division is used to solve the matrix equation XC = D. In this equation X and D are row vectors. It can be solved by multiplying on the right both sides by the inverse of C: X C C -1 = D C -1 X = D C -1 In MATLAB, the last equation can be written as: X = D/C UAE University, Faculty of Engineering, ERU Ayman Rabee 20
21 Left division is used to solve the matrix equation AX = B. In this equation X and B are row vectors. It can be solved by multiplying on the left both sides by the inverse of A: A A -1 X = A -1 B X = A -1 B In MATLAB, the last equation can be written as: X = A\B. The following example illustrates both left and right divisions to solve a set of linear equations. Example 3.6: A Set of Linear Equations Use matrix operation to solve the following set of linear equations: See the solution on the next page. UAE University, Faculty of Engineering, ERU Ayman Rabee 21
22 Solution: Using the rules explained earlier, the above system of equation can be written in matrix form AX=B or XC=D. (Note that this example can be solved using inv( ) function) [ ] [ ] [ ] [ ] [ ] [ ] >> A=[4-2 6;2 8 2;6 10 3] %Solving using the form AX=B A = >> B = [8;4;0] B = 8 4 Note the difference between A and C 0 >> X=A\B X = >> C=[4 2 6; ;6 2 3] %Solving using the form XC=D C = X and Xc are transpose of each other >> D=[8 4 0] D = >> Xc=D/C Xc = UAE University, Faculty of Engineering, ERU Ayman Rabee 22
23 Element-By-Element Operations These operations are carried out on each element of the array. Note that these operations are performed on arrays of the same size. Symbol Description Symbol Description.* Multiplication./ Right Division.^ Exponentiation.\ Left Division Example 3.7: >> A=[1 2 3;4 5 6] % Define 2x3 array A A = >> B=[5 7 4;6 2 9] % Define 2x3 array B B = >> A*B??? Error using ==> mtimes Inner matrix dimensions must agree. >> A.*B >> A./B >> A.^ Applying Library Functions The built-in functions applied to arrays as an element-by-element operation in which the input is an array and the output is also an array in which each element is calculated by applying the function to each element of the input array. For example, executing the command cos(a) will result in another array of same size as A with each element is the cosine of the corresponding element in A. Consider the following example. UAE University, Faculty of Engineering, ERU Ayman Rabee 23
24 Example 3.8: >> A=[1 5 70;pi 2*pi 3*pi] % Define 2x3 array A A = >> sin(a) % Apply the sin function >> sqrt(a) % Apply the sqrt function As said before, MATLAB has a large built-in Library functions. For example: sum(a): treats the columns of A as vectors, returning a row vector of the sums of each column, det(a): return the determinant of a square array A, std(a): returns a row vector containing the standard deviation of the elements of each column of A. You can use MATLAB help window for a complete list of all functions. Note that these functions can be applied to vectors. Example 3.9: >> A=[2 4 6;3 5 7; 1 2 3] A = >> sum(a) % Apply the sum function >> std(a) % Apply the standard deviation function >> sort(a) % Sorting array in an ascending order >> det(a) % Calculating the determinant 0 UAE University, Faculty of Engineering, ERU Ayman Rabee 24
25 Example of MATLAB Application - Amplitude modulation (AM): AM is a technique used in electronic communication, most commonly for transmitting information via a radio carrier wave. AM works by varying the strength of the transmitted signal in relation to the information being sent. For example, changes in the signal strength can be used to reflect the sounds to be reproduced by a speaker, or to specify the light intensity of television pixels. The AM signal is given by the following formula: ( ) ( ) ( ) Where m(t) is the message signal to be transmitted such as speech signal and f c is the frequency of the cosine (carrier) signal. Write a MATLAB m-file to simulate the AM single s(t) with the following parameters: t: time vector from 0 to 1 with step of f c : 15 Hz m(t): cosine signal with frequency of 5 Hz and amplitude of 8 volt Solution: % THIS M-FILE IS TO SIMULATE AMPLITUDE MODULATION SIGNAL % GIVEN BY: S(T)=M(T)*COS(2*PI*Fc*T) %time vector from 0 to 1 with step t=0:0.001:1; % Carrier signal vc = cos(2*pi*15*t); % transmitted signal m = 8*cos(2*pi*5*t); % AM signal s = m.*vc; % Plotting the signals figure(1) plot(t,vc) figure(2) plot(t,m) figure(3) plot(t,s) figure(n) command opens a new figure window with number specified by n plot(t,x) command will plot x vs. t such that t and x are of the same length or size UAE University, Faculty of Engineering, ERU Ayman Rabee 25
26 4. Execution Control In this section we are going to study some MATLAB structures used to weather execute a set of instructions or not, and how many times those set is going to be executed. Also we are going to discuss how to process 1-D and 2-D arrays with some of those structures. Specifically, the control structure covered here are: if-statements, while loop and for loop. 4.1 Relational and Logical Operators We have discussed the use of relational operators previously in section The logical operators in MATLAB are listed in table 4.1. Table 4.1 Logical Operators in MATLAB Logical Operator Name Description & AND Operates on two operands (A&B). If both results are true, the result is true. Otherwise the result is false OR Operates on two operands (A B). If either one or both are true, the result is true. Otherwise, the result is false ~ NOT Operates on one operand (~A). The result is true if the operand is false and false if the operand is true Note: The logical operators AND and OR listed above are element-by-element operators. That is, if the both operands are arrays, then they have to be of the same size. The outcome is an array of the same size with 1 s and 0 s according to the output of the operation at each position. 4.2 if Statements if evaluates a logical expression and executes a block of statements based on whether the logical expressions evaluates to true (logical 1) or false (logical 0). The general structure is as follows. if logical_expression 1 statements elseif logical_expression 2 statements... elseif logical_expression n statements else default statements end UAE University, Faculty of Engineering, ERU Ayman Rabee 26
27 If the logical_expression evaluates as true (logical 1), then the block of statements that follow if logical_expression are executed, otherwise the statements are skipped and program control is transferred to the eleseif logical_expression 2. If it is evaluated as true then the statements that follow it are executed, and so on so forth. Now, if none of the logical expressions are true, then the control is transferred to the else statement and the default statements are executed. Note: The only essential part of the general structure explained above is the first if statement, the statements that follow it, and the end statement. All other parts can be added according to the logic requirements. Example 4.1: Even or Odd clear;clc; n = 9; if round(n/2) == n/2 disp('even') % disp('...') used to display text else disp('odd') end Note that in the previous example, the function disp(... ) is used to display a text. Actually, this function can also be used to display an array without printing its name, for example: disp(a), where A is an array. Also that we can rewrite the previous example such that the m-file will ask the user to enter a number. We can do that by using the function input( ), i.e. n=input( Enter an Integer: ), then this message will appear on the command line waiting for the user to enter a number and then assigns the value to n. Example 4.2: clc;clear; n = input('enter an integer number: '); if round(n/2) == n/2 disp('even') % disp('...') used to display text else disp('odd') end 4.3 while Loop As in any programming language, the while loop is used to execute a set of statements many times (each time is called iteration or loops) until a specified condition is satisfied. The general structure of the while loop is as follows: UAE University, Faculty of Engineering, ERU Ayman Rabee 27
28 while logical_expression statements end The following examples illustrate the use of a while loop using m-file. Example 4.3: Generate a sequence of even numbers clc;clear; x=2 while x>=2 & x<=10 x=x+2 end The output displayed in the command window is: x = 2 x = 4 x = 6 x = 8 x = 10 x = 12 Example 4.4: Implied Loop clear;clc; x=[0:0.01:10]; y=sin(x); figure(1) plot(x,y) % to achieve the same result using while loop i = 1; while i<=1001 m = (i-1)*0.01; yy(i)=sin(m); xx(i)=m; % this is to create a time-vector x i = i+1; end figure(2) plot(xx,yy) In example 4.4, the first set is used to create a 1-D array x (vector) using the colon operator and 1-D array y (vector) using the sin( ) function. Each of them of size 1x1001(10/0.01+1=1001). We can do the same using a while loop. But we have to control how many times the loop will execute using i<=1001 and i=i+1. UAE University, Faculty of Engineering, ERU Ayman Rabee 28
29 4.4 for Loop The for loop is used to repeat a set of statements fixed number of times. The general structure is as follows: for i = initial_value : step_size : final_value statements end Note: the step size can be negative, but in this case the initial value should be greater than final value. If the step is omitted, then it defaults to one. Example 4.5: clc;clear; for i=1:3:10 x=i^2 end The output displayed in the command window is: x = 1 x = 16 x = 49 x = 100 So far, we have been displaying the values in the command line by omitting the semicolon operator from the end of each line we wish to display its output. In fact, MATLAB has a built-in function that can be used to display and control the format of the values displayed in the command line. This function is fprintf( ), which is similar to the function used in c to do the same operation. The general format of this function is: fprintf(format, variable) Let us rewrite the previous example using fprintf function. Example 4.6: clc;clear; for i=1:3:10 x=i^2; fprintf('x = %d\n',x) end The out displayed in the command window is: x = 1 x = 16 x = 49 x = 100 %d : decimal point notation \n : new line UAE University, Faculty of Engineering, ERU Ayman Rabee 29
30 Example 4.7: a vector is given by A = [-5,-17,-3,8,0,-1,12,-4,-6,6,-7,17]. Write a m-file that doubles the negative elements that are odd. clc;clear A = [-5,-17,-3,8,0,-1,12,-4,-6,6,-7,17]; disp('a Before = ') disp(a) for i=1:length(a) if (A(i)<0) & (A(i)/2 ~= round(a(i)/2)) A(i) = A(i)*2; end end disp('a After = ') disp(a) The output displayed in the command line: A Before = A After = UAE University, Faculty of Engineering, ERU Ayman Rabee 30
31 5. User Defined Functions In this section we are going to discuss how to define user defined functions, how data are passed to a function and how data are returned from functions Function Definition User defined functions must be stored in a separate m-file and in your directory of work. And the m-file that contains your function should be saved with same name as the function. The general definition of a function is as follows: function [output_vars] = function_name (input_vars) %optional documentation function code body Note that if you have one output variable, then omit the brackets [ ]. Those only used if you have more than output variable. Consider the following two examples. Example 5.1: Write a MATLAB function file for f(x) = x 2 +2x+3. Then calculate f(0) and f(3). Solution: create a new m-file, save it as f.m and then write your code. Figure 5.1 shows the required function. Note that the name of the file should match the name of the function You can call the function in the command line using its name as follows: >> f(0) 3 >> f(6) 51 UAE University, Faculty of Engineering, ERU Ayman Rabee 31
32 Example 5.2: Write MATLAB function to calculate the area and circumference of a circle for given radius r. We should follow the same steps used in the previous example, but here use another name, let us say circle.m. Note that since we have two output variables, they have to be enclosed by [ ]. function [area,cercom]=circle(radius) %Function to compute area and %circumference of a circle area = pi*radius^2; cercom = 2*pi*radius; The circle function can be used in the command line as follows: >> [a,c]=circle(4) a = c = >> [a,c]=circle(1) a = c = a: area c: circumference UAE University, Faculty of Engineering, ERU Ayman Rabee 32
33 6. 2-D Plots 6.1 Basic 2-D Plots The most basic and perhaps most useful command for producing a simple 2-D plots is the plot( ) command. plot(xvalues, yvalues, style-option ) where: xvalues and yvalues are vectors of the same length containing x and y coordinates of points on the graph. style-option is an optional arguments that specifies the color, the line style (e.g., solid, dashed, dotted,etc.) and the point-marker style (e.g., o, +, *, etc.). All three options can be specified together as the syle-option in the general form: color_linestyle_markerstyle. Style Option The style-option in the plot command is a character string that consists of one, two or three characters that specify the color and/or line style. There are several color, line and marker style option as shown in figure 6.1. Table 6.1: Style option for the color, line and marker styles Color style-option Line style-option Marker style-option y yellow - solid + plus sign m magenta -- dashed o circle c cyan : dotted * asterisk r red -. dash-dot x x-mark g green. point b blue ^ up triangle w white s square k black d diamond Examples plot(x,y) plots y vs. x with a blue solid line (default) plot(x,y,'r') plots y vs. x with a red solid line plot(x,y,':') plots y vs. x with a dotted line plot(x,y,'b--') plot y vs. x with a blue dashed line plot(x,y,'+') plot y vs. x as unconnected points marked by + UAE University, Faculty of Engineering, ERU Ayman Rabee 33
34 Example 6.1: Plot the function y = x cos(6x), where -2 x 4 using different line styles. clc;clear x=-2:0.01:4; y=3.5.^(-0.5*x).*cos(6*x); figure(1) plot(x,y) figure(2) plot(x,y,'r') figure(3) plot(x,y,':') figure(4) plot(x,y,'b--') figure(5) plot(x,y,'+') UAE University, Faculty of Engineering, ERU Ayman Rabee 34
35 Also we can plot more than one graph on the same plot by typing pairs of vectors in the plot command, for example: plot(x,y, g-- x,z, r-. ) Example 6.2: clc;clear x=-pi:1/pi:pi; y=cos(x); z=sin(x); plot(x,y,'g--',x,z,'r-.') % Add grid lines grid on % Remove grid lines (uncomment next line) %grid off Formatting a Plot A figure that contains a plot needs to be formatted to have a specific look and to display information in addition to the graph itself. Consider the following commands: xlabel( x-axis label ) ylabel( y-axis label ) title( title of the figure ) axis([xmin xmax ymin ymax]) UAE University, Faculty of Engineering, ERU Ayman Rabee 35
36 Example 6.3: clc;clear t = 0:0.001:1; f = 15; y = cos(2*pi*f*t); plot(t,y,'--') xlabel('time (sec)') ylabel('cos(2\pift)') title('t vs. cos(2\pift)') grid on 6.2 Subplots Sometimes it is required to place plots side by side. The command subplot( ) can be used to set and design the required layout. subplot(rows,columns,index) This function divides the graphics window into rows x columns sub-windows and puts a certain plot in a position specified by the index. For example the two commands subplot(2,2,3), plot(x,y) divides the graphics window into 4 sub-windows and places the plot of y vs. x in the third sub-window. See example 6.4. Example 6.4: UAE University, Faculty of Engineering, ERU Ayman Rabee 36
37 clc;clear t = -0.5:0.001:0.5; f = 15; x = cos(2*pi*f*t); y = sin(2*pi*f*t); z = sinc(2*pi*f*t); w = 0.5*t-0.5; subplot(2,2,1) plot(t,x) grid on title('cosine vs. time') subplot(2,2,2) plot(t,y) grid on title('sine vs. time') subplot(2,2,3) plot(t,z) grid on title('sinc vs. time') subplot(2,2,4) plot(t,w) grid on title('w vs. time') subplot(2,2,1) subplot(2,2,2) subplot(2,2,3) subplot(2,2,4) UAE University, Faculty of Engineering, ERU Ayman Rabee 37
Introduction To MATLAB Introduction to Programming GENG 200
Introduction To MATLAB Introduction to Programming GENG 200, Prepared by Ali Abu Odeh 1 Table of Contents M Files 2 4 2 Execution Control 3 Vectors User Defined Functions Expected Chapter Duration: 6 classes.
More informationPART 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 informationIntroduction 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 informationPowerPoints 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 informationChapter 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 informationWhat 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 informationProgramming 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 informationMATLAB 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 informationIntroduction 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 informationIntroduction 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 informationLecture 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 informationIntroduction 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 information1. Register an account on: using your Oxford address
1P10a MATLAB 1.1 Introduction MATLAB stands for Matrix Laboratories. It is a tool that provides a graphical interface for numerical and symbolic computation along with a number of data analysis, simulation
More informationChapter 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 informationMATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab
MATH 495.3 (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab Below is a screen similar to what you should see when you open Matlab. The command window is the large box to the right containing the
More informationIntroduction to Matlab
What is Matlab? Introduction to Matlab Matlab is software written by a company called The Mathworks (mathworks.com), and was first created in 1984 to be a nice front end to the numerical routines created
More informationFinding, 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 information12 whereas if I terminate the expression with a semicolon, the printed output is suppressed.
Example 4 Printing and Plotting Matlab provides numerous print and plot options. This example illustrates the basics and provides enough detail that you can use it for typical classroom work and assignments.
More informationMATLAB 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 informationMATLAB SUMMARY FOR MATH2070/2970
MATLAB SUMMARY FOR MATH2070/2970 DUNCAN SUTHERLAND 1. Introduction The following is inted as a guide containing all relevant Matlab commands and concepts for MATH2070 and 2970. All code fragments should
More information1 Introduction to Matlab
1 Introduction to Matlab 1. What is Matlab? Matlab is a computer program designed to do mathematics. You might think of it as a super-calculator. That is, once Matlab has been started, you can enter computations,
More informationMatlab 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 informationMATLAB 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 informationLabVIEW MathScript Quick Reference
Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics LabVIEW MathScript Quick Reference Hans-Petter Halvorsen, 2012.06.14 Faculty of Technology, Postboks
More information2.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 informationLecturer: 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 informationQUICK 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 informationIntroduction to MATLAB for Engineers, Third Edition
PowerPoint to accompany Introduction to MATLAB for Engineers, Third Edition William J. Palm III Chapter 2 Numeric, Cell, and Structure Arrays Copyright 2010. The McGraw-Hill Companies, Inc. This work is
More informationInteractive 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 informationELEC4042 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 informationLab 1 Intro to MATLAB and FreeMat
Lab 1 Intro to MATLAB and FreeMat Objectives concepts 1. Variables, vectors, and arrays 2. Plotting data 3. Script files skills 1. Use MATLAB to solve homework problems 2. Plot lab data and mathematical
More informationMatlab 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 informationMath 375 Natalia Vladimirova (many ideas, examples, and excersises are borrowed from Profs. Monika Nitsche, Richard Allen, and Stephen Lau)
Natalia Vladimirova (many ideas, examples, and excersises are borrowed from Profs. Monika Nitsche, Richard Allen, and Stephen Lau) January 24, 2010 Starting Under windows Click on the Start menu button
More informationExperiment 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 informationDigital 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 informationMATLAB 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 informationIntroduction 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 informationLaboratory 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 informationEric W. Hansen. The basic data type is a matrix This is the basic paradigm for computation with MATLAB, and the key to its power. Here s an example:
Using MATLAB for Stochastic Simulation. Eric W. Hansen. Matlab Basics Introduction MATLAB (MATrix LABoratory) is a software package designed for efficient, reliable numerical computing. Using MATLAB greatly
More informationA 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 informationIntroduction to Matlab
Introduction to Matlab November 22, 2013 Contents 1 Introduction to Matlab 1 1.1 What is Matlab.................................. 1 1.2 Matlab versus Maple............................... 2 1.3 Getting
More informationA 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 informationAN 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 informationIntroduction to MATLAB
CHEE MATLAB Tutorial Introduction to MATLAB Introduction In this tutorial, you will learn how to enter matrices and perform some matrix operations using MATLAB. MATLAB is an interactive program for numerical
More informationDr 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 informationProf. Manoochehr Shirzaei. RaTlab.asu.edu
RaTlab.asu.edu Introduction To MATLAB Introduction To MATLAB This lecture is an introduction of the basic MATLAB commands. We learn; Functions Procedures for naming and saving the user generated files
More informationIntroduction 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 informationIntroduction to Octave/Matlab. Deployment of Telecommunication Infrastructures
Introduction to Octave/Matlab Deployment of Telecommunication Infrastructures 1 What is Octave? Software for numerical computations and graphics Particularly designed for matrix computations Solving equations,
More informationIntroduction to MATLAB 7 for Engineers
PowerPoint to accompany Introduction to MATLAB 7 for Engineers William J. Palm III Chapter 2 Numeric, Cell, and Structure Arrays Copyright 2005. The McGraw-Hill Companies, Inc. Permission required for
More informationDSP 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 informationMatlab 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 informationProgramming 1. Script files. help cd Example:
Programming Until now we worked with Matlab interactively, executing simple statements line by line, often reentering the same sequences of commands. Alternatively, we can store the Matlab input commands
More informationIntroduction 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 informationWhat is Matlab? A software environment for interactive numerical computations
What is Matlab? A software environment for interactive numerical computations Examples: Matrix computations and linear algebra Solving nonlinear equations Numerical solution of differential equations Mathematical
More informationTable of Contents. Basis CEMTool 7 Tutorial
PREFACE CEMTool (Computer-aided Engineering & Mathematics Tool) is a useful computational tool in science and engineering. No matter what you background be it physics, chemistry, math, or engineering it
More informationTo 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 informationLab 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 informationINTRODUCTION TO MATLAB
1 of 18 BEFORE YOU BEGIN PREREQUISITE LABS None EXPECTED KNOWLEDGE Algebra and fundamentals of linear algebra. EQUIPMENT None MATERIALS None OBJECTIVES INTRODUCTION TO MATLAB After completing this lab
More informationMATLAB Introduction to MATLAB Programming
MATLAB Introduction to MATLAB Programming MATLAB Scripts So far we have typed all the commands in the Command Window which were executed when we hit Enter. Although every MATLAB command can be executed
More informationIntroduction to Matlab
Introduction to Matlab Math 339 Fall 2013 First, put the icon in the launcher: Drag and drop Now, open Matlab: * Current Folder * Command Window * Workspace * Command History Operations in Matlab Description:
More informationSome elements for Matlab programming
Some elements for Matlab programming Nathalie Thomas 2018 2019 Matlab, which stands for the abbreviation of MATrix LABoratory, is one of the most popular language for scientic computation. The classical
More informationMATLAB Lesson I. Chiara Lelli. October 2, Politecnico di Milano
MATLAB Lesson I Chiara Lelli Politecnico di Milano October 2, 2012 MATLAB MATLAB (MATrix LABoratory) is an interactive software system for: scientific computing statistical analysis vector and matrix computations
More informationMatlab 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 informationIntroduction 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 informationMATLAB: The Basics. Dmitry Adamskiy 9 November 2011
MATLAB: The Basics Dmitry Adamskiy adamskiy@cs.rhul.ac.uk 9 November 2011 1 Starting Up MATLAB Windows users: Start up MATLAB by double clicking on the MATLAB icon. Unix/Linux users: Start up by typing
More informationMATLAB and Numerical Analysis
School of Mechanical Engineering Pusan National University dongwoonkim@pusan.ac.kr Teaching Assistant 김동운 dongwoonkim@pusan.ac.kr 윤종희 jongheeyun@pusan.ac.kr Lab office: 통합기계관 120호 ( 510-3921) 방사선영상연구실홈페이지
More informationselected topic in transportation 2552/2. 1 Prepared by Lect.Weerakaset Suanpaga
203484 selected topic in transportation 2552/2 Introduction ti to MATLAB 1 Prepared by Lect.Weerakaset Suanpaga Outline Introduction and where to get MATLAB Data structure: matrices, vectors and operations
More informationMAT 275 Laboratory 1 Introduction to MATLAB
MATLAB sessions: Laboratory 1 1 MAT 275 Laboratory 1 Introduction to MATLAB MATLAB is a computer software commonly used in both education and industry to solve a wide range of problems. This Laboratory
More informationIntroduction to Matlab
Introduction to Matlab What is Matlab The software program called Matlab (short for MATrix LABoratory) is arguably the world standard for engineering- mainly because of its ability to do very quick prototyping.
More informationConstraint-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 informationInlichtingenblad, 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 informationMATLAB Vocabulary. Gerald Recktenwald. Version 0.965, 25 February 2017
MATLAB Vocabulary Gerald Recktenwald Version 0.965, 25 February 2017 MATLAB is a software application for scientific computing developed by the Mathworks. MATLAB runs on Windows, Macintosh and Unix operating
More informationAMATH 352: MATLAB Tutorial written by Peter Blossey Department of Applied Mathematics University of Washington Seattle, WA
AMATH 352: MATLAB Tutorial written by Peter Blossey Department of Applied Mathematics University of Washington Seattle, WA MATLAB (short for MATrix LABoratory) is a very useful piece of software for numerical
More informationMATLAB 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 informationAppendix 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 informationMcTutorial: A MATLAB Tutorial
McGill University School of Computer Science Sable Research Group McTutorial: A MATLAB Tutorial Lei Lopez Last updated: August 2014 w w w. s a b l e. m c g i l l. c a Contents 1 MATLAB BASICS 3 1.1 MATLAB
More informationAMS 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 informationMATLAB Tutorial III Variables, Files, Advanced Plotting
MATLAB Tutorial III Variables, Files, Advanced Plotting A. Dealing with Variables (Arrays and Matrices) Here's a short tutorial on working with variables, taken from the book, Getting Started in Matlab.
More informationELEN 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 informationChapter 2 (Part 2) MATLAB Basics. dr.dcd.h CS 101 /SJC 5th Edition 1
Chapter 2 (Part 2) MATLAB Basics dr.dcd.h CS 101 /SJC 5th Edition 1 Display Format In the command window, integers are always displayed as integers Characters are always displayed as strings Other values
More informationEE 301 Lab 1 Introduction to MATLAB
EE 301 Lab 1 Introduction to MATLAB 1 Introduction In this lab you will be introduced to MATLAB and its features and functions that are pertinent to EE 301. This lab is written with the assumption that
More informationPC-MATLAB PRIMER. This is intended as a guided tour through PCMATLAB. Type as you go and watch what happens.
PC-MATLAB PRIMER This is intended as a guided tour through PCMATLAB. Type as you go and watch what happens. >> 2*3 ans = 6 PCMATLAB uses several lines for the answer, but I ve edited this to save space.
More informationIntroduction 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 informationMechanical Engineering Department Second Year (2015)
Lecture 7: Graphs Basic Plotting 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
More informationSummer 2009 REU: Introduction to Matlab
Summer 2009 REU: Introduction to Matlab Moysey Brio & Paul Dostert June 29, 2009 1 / 19 Using Matlab for the First Time Click on Matlab icon (Windows) or type >> matlab & in the terminal in Linux. Many
More informationHow 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 informationLab #1 Revision to MATLAB
Lab #1 Revision to MATLAB Objectives In this lab we would have a revision to MATLAB, especially the basic commands you have dealt with in analog control. 1. What Is MATLAB? MATLAB is a high-performance
More informationIntroductory MATLAB. Appendix A A.1 BACKGROUND A.2 STARTING WITH MATLAB. Core Topics
Appendix A Introductory MATLAB Core Topics Starting with MATLAB (A.2). Arrays (A.3). Mathematical operations with arrays (A.4). Script files (A.5). User-defined functions and function files (A.7). Anonymous
More informationIntroduction 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 informationPart #1. A0B17MTB Matlab. Miloslav Čapek Filip Kozák, Viktor Adler, Pavel Valtr
A0B17MTB Matlab Part #1 Miloslav Čapek miloslav.capek@fel.cvut.cz Filip Kozák, Viktor Adler, Pavel Valtr Department of Electromagnetic Field B2-626, Prague You will learn Scalars, vectors, matrices (class
More informationMAT 343 Laboratory 1 Matrix and Vector Computations in MATLAB
MAT 343 Laboratory 1 Matrix and Vector Computations in MATLAB MATLAB is a computer software commonly used in both education and industry to solve a wide range of problems. This Laboratory provides a brief
More informationLogical 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 informationGetting 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 informationOUTLINES. Variable names in MATLAB. Matrices, Vectors and Scalar. Entering a vector Colon operator ( : ) Mathematical operations on vectors.
1 LECTURE 3 OUTLINES Variable names in MATLAB Examples Matrices, Vectors and Scalar Scalar Vectors Entering a vector Colon operator ( : ) Mathematical operations on vectors examples 2 VARIABLE NAMES IN
More informationIntroduction. Matlab for Psychologists. Overview. Coding v. button clicking. Hello, nice to meet you. Variables
Introduction Matlab for Psychologists Matlab is a language Simple rules for grammar Learn by using them There are many different ways to do each task Don t start from scratch - build on what other people
More informationObjectives. 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 informationGetting Started with Matlab
Chapter Getting Started with Matlab The computational examples and exercises in this book have been computed using Matlab, which is an interactive system designed specifically for scientific computation
More informationMATLAB TUTORIAL WORKSHEET
MATLAB TUTORIAL WORKSHEET What is MATLAB? Software package used for computation High-level programming language with easy to use interactive environment Access MATLAB at Tufts here: https://it.tufts.edu/sw-matlabstudent
More informationIntroduction 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 informationMATLAB Basics. Mohamed Taha. Communication Engineering Department Princess Sumaya University Page 1 of 32. Full Screen.
Mohamed Taha Communication Engineering Department Princess Sumaya University mtaha@psut.edu.jo Page 1 of 32 1 What is It is an abbreviation to MATrix LABoratory Front end for a matrix library It is an
More information