MATLAB – Simulink

MATLAB – Simulink ”; Previous Next Simulink is a simulation and model-based design environment for dynamic and embedded systems, integrated with MATLAB. Simulink, also developed by MathWorks, is a data flow graphical programming language tool for modelling, simulating and analyzing multi-domain dynamic systems. It is basically a graphical block diagramming tool with customizable set of block libraries. It allows you to incorporate MATLAB algorithms into models as well as export the simulation results into MATLAB for further analysis. Simulink supports − system-level design simulation automatic code generation testing and verification of embedded systems There are several other add-on products provided by MathWorks and third-party hardware and software products that are available for use with Simulink. The following list gives brief description of some of them − Stateflow allows developing state machines and flow charts. Simulink Coder allows the generation of C source code for real-time implementation of systems automatically. xPC Target together with x86-based real-time systems provide an environment to simulate and test Simulink and Stateflow models in real-time on the physical system. Embedded Coder supports specific embedded targets. HDL Coder allows to automatically generate synthesizable VHDL and Verilog. SimEvents provides a library of graphical building blocks for modelling queuing systems. Simulink is capable of systematic verification and validation of models through modelling style checking, requirements traceability and model coverage analysis. Simulink Design Verifier allows you to identify design errors and to generate test case scenarios for model checking. Using Simulink To open Simulink, type in the MATLAB work space − simulink Simulink opens with the Library Browser. The Library Browser is used for building simulation models. On the left side window pane, you will find several libraries categorized on the basis of various systems, clicking on each one will display the design blocks on the right window pane. Building Models To create a new model, click the New button on the Library Browser”s toolbar. This opens a new untitled model window. A Simulink model is a block diagram. Model elements are added by selecting the appropriate elements from the Library Browser and dragging them into the Model window. Alternately, you can copy the model elements and paste them into the model window. Examples Drag and drop items from the Simulink library to make your project. For the purpose of this example, two blocks will be used for the simulation – A Source (a signal) and a Sink (a scope). A signal generator (the source) generates an analog signal, which will then be graphically visualized by the scope(the sink). Begin by dragging the required blocks from the library to the project window. Then, connect the blocks together which can be done by dragging connectors from connection points on one block to those of another. Let us drag a ”Sine Wave” block into the model. Select ”Sinks” from the library and drag a ”Scope” block into the model. Drag a signal line from the output of the Sine Wave block to the input of the Scope block. Run the simulation by pressing the ”Run” button, keeping all parameters default (you can change them from the Simulation menu) You should get the below graph from the scope. Print Page Previous Next Advertisements ”;

MATLAB – Discussion

Discuss MATLAB ”; Previous Next MATLAB is a programming language developed by MathWorks. It started out as a matrix programming language where linear algebra programming was simple. It can be run both under interactive sessions and as a batch job. This tutorial gives you aggressively a gentle introduction of MATLAB programming language. It is designed to give students fluency in MATLAB programming language. Problem-based MATLAB examples have been given in simple and easy way to make your learning fast and effective. Print Page Previous Next Advertisements ”;

MATLAB – Quick Guide

MATLAB – Quick Guide ”; Previous Next MATLAB – Overview MATLAB (matrix laboratory) is a fourth-generation high-level programming language and interactive environment for numerical computation, visualization and programming. MATLAB is developed by MathWorks. It allows matrix manipulations; plotting of functions and data; implementation of algorithms; creation of user interfaces; interfacing with programs written in other languages, including C, C++, Java, and FORTRAN; analyze data; develop algorithms; and create models and applications. It has numerous built-in commands and math functions that help you in mathematical calculations, generating plots, and performing numerical methods. MATLAB”s Power of Computational Mathematics MATLAB is used in every facet of computational mathematics. Following are some commonly used mathematical calculations where it is used most commonly − Dealing with Matrices and Arrays 2-D and 3-D Plotting and graphics Linear Algebra Algebraic Equations Non-linear Functions Statistics Data Analysis Calculus and Differential Equations Numerical Calculations Integration Transforms Curve Fitting Various other special functions Features of MATLAB Following are the basic features of MATLAB − It is a high-level language for numerical computation, visualization and application development. It also provides an interactive environment for iterative exploration, design and problem solving. It provides vast library of mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, numerical integration and solving ordinary differential equations. It provides built-in graphics for visualizing data and tools for creating custom plots. MATLAB”s programming interface gives development tools for improving code quality maintainability and maximizing performance. It provides tools for building applications with custom graphical interfaces. It provides functions for integrating MATLAB based algorithms with external applications and languages such as C, Java, .NET and Microsoft Excel. Uses of MATLAB MATLAB is widely used as a computational tool in science and engineering encompassing the fields of physics, chemistry, math and all engineering streams. It is used in a range of applications including − Signal Processing and Communications Image and Video Processing Control Systems Test and Measurement Computational Finance Computational Biology MATLAB – Environment Setup Local Environment Setup Setting up MATLAB environment is a matter of few clicks. The installer can be downloaded from here. MathWorks provides the licensed product, a trial version and a student version as well. You need to log into the site and wait a little for their approval. After downloading the installer the software can be installed through few clicks. Understanding the MATLAB Environment MATLAB development IDE can be launched from the icon created on the desktop. The main working window in MATLAB is called the desktop. When MATLAB is started, the desktop appears in its default layout − The desktop has the following panels − Current Folder − This panel allows you to access the project folders and files. Command Window − This is the main area where commands can be entered at the command line. It is indicated by the command prompt (>>). Workspace − The workspace shows all the variables created and/or imported from files. Command History − This panel shows or return commands that are entered at the command line. Set up GNU Octave If you are willing to use Octave on your machine ( Linux, BSD, OS X or Windows ), then kindly download latest version from Download GNU Octave. You can check the given installation instructions for your machine. MATLAB – Basic Syntax MATLAB environment behaves like a super-complex calculator. You can enter commands at the >> command prompt. MATLAB is an interpreted environment. In other words, you give a command and MATLAB executes it right away. Hands on Practice Type a valid expression, for example, Live Demo 5 + 5 And press ENTER When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 10 Let us take up few more examples − Live Demo 3 ^ 2 % 3 raised to the power of 2 When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 9 Another example, Live Demo sin(pi /2) % sine of angle 90o When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 1 Another example, Live Demo 7/0 % Divide by zero When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = Inf warning: division by zero Another example, Live Demo 732 * 20.3 When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − ans = 1.4860e+04 MATLAB provides some special expressions for some mathematical symbols, like pi for π, Inf for ∞, i (and j) for √-1 etc. Nan stands for ”not a number”. Use of Semicolon (;) in MATLAB Semicolon (;) indicates end of statement. However, if you want to suppress and hide the MATLAB output for an expression, add a semicolon after the expression. For example, Live Demo x = 3; y = x + 5 When you click the Execute button, or type Ctrl+E, MATLAB executes it immediately and the result returned is − y = 8 Adding Comments The percent symbol (%) is used for indicating a comment line. For example, x = 9 % assign the value 9 to x You can also write a block of comments using the block comment operators % { and % }. The MATLAB editor includes tools and context menu items to help you add, remove, or change the format of comments. Commonly used Operators and Special Characters MATLAB supports the following commonly used operators and special characters − Operator Purpose + Plus; addition operator. – Minus; subtraction operator. * Scalar and matrix multiplication operator. .* Array multiplication operator. ^ Scalar and matrix exponentiation operator. .^ Array exponentiation operator. Left-division operator. / Right-division operator. . Array left-division operator. ./ Array right-division operator. : Colon; generates regularly spaced elements and represents an entire row or column. ( ) Parentheses; encloses function arguments and array

MATLAB – Calculus

MATLAB – Calculus ”; Previous Next MATLAB provides various ways for solving problems of differential and integral calculus, solving differential equations of any degree and calculation of limits. Best of all, you can easily plot the graphs of complex functions and check maxima, minima and other stationery points on a graph by solving the original function, as well as its derivative. This chapter will deal with problems of calculus. In this chapter, we will discuss pre-calculus concepts i.e., calculating limits of functions and verifying the properties of limits. In the next chapter Differential, we will compute derivative of an expression and find the local maxima and minima on a graph. We will also discuss solving differential equations. Finally, in the Integration chapter, we will discuss integral calculus. Calculating Limits MATLAB provides the limit function for calculating limits. In its most basic form, the limit function takes expression as an argument and finds the limit of the expression as the independent variable goes to zero. For example, let us calculate the limit of a function f(x) = (x3 + 5)/(x4 + 7), as x tends to zero. syms x limit((x^3 + 5)/(x^4 + 7)) MATLAB will execute the above statement and return the following result − ans = 5/7 The limit function falls in the realm of symbolic computing; you need to use the syms function to tell MATLAB which symbolic variables you are using. You can also compute limit of a function, as the variable tends to some number other than zero. To calculate lim x->a(f(x)), we use the limit command with arguments. The first being the expression and the second is the number, that x approaches, here it is a. For example, let us calculate limit of a function f(x) = (x-3)/(x-1), as x tends to 1. limit((x – 3)/(x-1),1) MATLAB will execute the above statement and return the following result − ans = NaN Let”s take another example, limit(x^2 + 5, 3) MATLAB will execute the above statement and return the following result − ans = 14 Calculating Limits using Octave Following is Octave version of the above example using symbolic package, try to execute and compare the result − pkg load symbolic symbols x = sym(“x”); subs((x^3+5)/(x^4+7),x,0) Octave will execute the above statement and return the following result − ans = 0.7142857142857142857 Verification of Basic Properties of Limits Algebraic Limit Theorem provides some basic properties of limits. These are as follows − Let us consider two functions − f(x) = (3x + 5)/(x – 3) g(x) = x2 + 1. Let us calculate the limits of the functions as x tends to 5, of both functions and verify the basic properties of limits using these two functions and MATLAB. Example Create a script file and type the following code into it − syms x f = (3*x + 5)/(x-3); g = x^2 + 1; l1 = limit(f, 4) l2 = limit (g, 4) lAdd = limit(f + g, 4) lSub = limit(f – g, 4) lMult = limit(f*g, 4) lDiv = limit (f/g, 4) When you run the file, it displays − l1 = 17 l2 = 17 lAdd = 34 lSub = 0 lMult = 289 lDiv = 1 Verification of Basic Properties of Limits using Octave Following is Octave version of the above example using symbolic package, try to execute and compare the result − pkg load symbolic symbols x = sym(“x”); f = (3*x + 5)/(x-3); g = x^2 + 1; l1 = subs(f, x, 4) l2 = subs (g, x, 4) lAdd = subs (f+g, x, 4) lSub = subs (f-g, x, 4) lMult = subs (f*g, x, 4) lDiv = subs (f/g, x, 4) Octave will execute the above statement and return the following result − l1 = 17.0 l2 = 17.0 lAdd = 34.0 lSub = 0.0 lMult = 289.0 lDiv = 1.0 Left and Right Sided Limits When a function has a discontinuity for some particular value of the variable, the limit does not exist at that point. In other words, limits of a function f(x) has discontinuity at x = a, when the value of limit, as x approaches x from left side, does not equal the value of the limit as x approaches from right side. This leads to the concept of left-handed and right-handed limits. A left-handed limit is defined as the limit as x -> a, from the left, i.e., x approaches a, for values of x < a. A right-handed limit is defined as the limit as x -> a, from the right, i.e., x approaches a, for values of x > a. When the left-handed limit and right-handed limit are not equal, the limit does not exist. Let us consider a function − f(x) = (x – 3)/|x – 3| We will show that limx->3 f(x) does not exist. MATLAB helps us to establish this fact in two ways − By plotting the graph of the function and showing the discontinuity. By computing the limits and showing that both are different. The left-handed and right-handed limits are computed by passing the character strings ”left” and ”right” to the limit command as the last argument. Example Create a script file and type the following code into it − f = (x – 3)/abs(x-3); ezplot(f,[-1,5]) l = limit(f,x,3,”left”) r = limit(f,x,3,”right”) When you run the file, MATLAB draws the following plot After this following output is displayed − l = -1 r = 1 Print Page Previous Next Advertisements ”;

MATLAB – Matrix

MATLAB – Matrix ”; Previous Next A matrix is a two-dimensional array of numbers. In MATLAB, you create a matrix by entering elements in each row as comma or space delimited numbers and using semicolons to mark the end of each row. For example, let us create a 4-by-5 matrix a − Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8] MATLAB will execute the above statement and return the following result − a = 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 Referencing the Elements of a Matrix To reference an element in the mth row and nth column, of a matrix mx, we write − mx(m, n); For example, to refer to the element in the 2nd row and 5th column, of the matrix a, as created in the last section, we type − Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; a(2,5) MATLAB will execute the above statement and return the following result − ans = 6 To reference all the elements in the mth column we type A(:,m). Let us create a column vector v, from the elements of the 4th row of the matrix a − Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; v = a(:,4) MATLAB will execute the above statement and return the following result − v = 4 5 6 7 You can also select the elements in the mth through nth columns, for this we write − a(:,m:n) Let us create a smaller matrix taking the elements from the second and third columns − Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; a(:, 2:3) MATLAB will execute the above statement and return the following result − ans = 2 3 3 4 4 5 5 6 In the same way, you can create a sub-matrix taking a sub-part of a matrix. Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; a(:, 2:3) MATLAB will execute the above statement and return the following result − ans = 2 3 3 4 4 5 5 6 In the same way, you can create a sub-matrix taking a sub-part of a matrix. For example, let us create a sub-matrix sa taking the inner subpart of a − 3 4 5 4 5 6 To do this, write − Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; sa = a(2:3,2:4) MATLAB will execute the above statement and return the following result − sa = 3 4 5 4 5 6 Deleting a Row or a Column in a Matrix You can delete an entire row or column of a matrix by assigning an empty set of square braces [] to that row or column. Basically, [] denotes an empty array. For example, let us delete the fourth row of a − Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; a( 4 , : ) = [] MATLAB will execute the above statement and return the following result − a = 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 Next, let us delete the fifth column of a − Live Demo a = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8]; a(: , 5)=[] MATLAB will execute the above statement and return the following result − a = 1 2 3 4 2 3 4 5 3 4 5 6 4 5 6 7 Example In this example, let us create a 3-by-3 matrix m, then we will copy the second and third rows of this matrix twice to create a 4-by-3 matrix. Create a script file with the following code − Live Demo a = [ 1 2 3 ; 4 5 6; 7 8 9]; new_mat = a([2,3,2,3],:) When you run the file, it displays the following result − new_mat = 4 5 6 7 8 9 4 5 6 7 8 9 Matrix Operations In this section, let us discuss the following basic and commonly used matrix operations − Addition and Subtraction of Matrices Division of Matrices Scalar Operations of Matrices Transpose of a Matrix Concatenating Matrices Matrix Multiplication Determinant of a Matrix Inverse of a Matrix Print Page Previous Next Advertisements ”;

MATLAB – Operators

MATLAB – Operators ”; Previous Next An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. MATLAB is designed to operate primarily on whole matrices and arrays. Therefore, operators in MATLAB work both on scalar and non-scalar data. MATLAB allows the following types of elementary operations − Arithmetic Operators Relational Operators Logical Operators Bitwise Operations Set Operations Arithmetic Operators MATLAB allows two different types of arithmetic operations − Matrix arithmetic operations Array arithmetic operations Matrix arithmetic operations are same as defined in linear algebra. Array operations are executed element by element, both on one-dimensional and multidimensional array. The matrix operators and array operators are differentiated by the period (.) symbol. However, as the addition and subtraction operation is same for matrices and arrays, the operator is same for both cases. The following table gives brief description of the operators − Show Examples Sr.No. Operator & Description 1 + Addition or unary plus. A+B adds the values stored in variables A and B. A and B must have the same size, unless one is a scalar. A scalar can be added to a matrix of any size. 2 – Subtraction or unary minus. A-B subtracts the value of B from A. A and B must have the same size, unless one is a scalar. A scalar can be subtracted from a matrix of any size. 3 * Matrix multiplication. C = A*B is the linear algebraic product of the matrices A and B. More precisely, For non-scalar A and B, the number of columns of A must be equal to the number of rows of B. A scalar can multiply a matrix of any size. 4 .* Array multiplication. A.*B is the element-by-element product of the arrays A and B. A and B must have the same size, unless one of them is a scalar. 5 / Slash or matrix right division. B/A is roughly the same as B*inv(A). More precisely, B/A = (A”B”)”. 6 ./ Array right division. A./B is the matrix with elements A(i,j)/B(i,j). A and B must have the same size, unless one of them is a scalar. 7 Backslash or matrix left division. If A is a square matrix, AB is roughly the same as inv(A)*B, except it is computed in a different way. If A is an n-by-n matrix and B is a column vector with n components, or a matrix with several such columns, then X = AB is the solution to the equation AX = B. A warning message is displayed if A is badly scaled or nearly singular. 8 . Array left division. A.B is the matrix with elements B(i,j)/A(i,j). A and B must have the same size, unless one of them is a scalar. 9 ^ Matrix power. X^p is X to the power p, if p is a scalar. If p is an integer, the power is computed by repeated squaring. If the integer is negative, X is inverted first. For other values of p, the calculation involves eigenvalues and eigenvectors, such that if [V,D] = eig(X), then X^p = V*D.^p/V. 10 .^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. A and B must have the same size, unless one of them is a scalar. 11 ” Matrix transpose. A” is the linear algebraic transpose of A. For complex matrices, this is the complex conjugate transpose. 12 .” Array transpose. A.” is the array transpose of A. For complex matrices, this does not involve conjugation. Relational Operators Relational operators can also work on both scalar and non-scalar data. Relational operators for arrays perform element-by-element comparisons between two arrays and return a logical array of the same size, with elements set to logical 1 (true) where the relation is true and elements set to logical 0 (false) where it is not. The following table shows the relational operators available in MATLAB − Show Examples Sr.No. Operator & Description 1 < Less than 2 <= Less than or equal to 3 > Greater than 4 >= Greater than or equal to 5 == Equal to 6 ~= Not equal to Logical Operators MATLAB offers two types of logical operators and functions − Element-wise − These operators operate on corresponding elements of logical arrays. Short-circuit − These operators operate on scalar and, logical expressions. Element-wise logical operators operate element-by-element on logical arrays. The symbols &, |, and ~ are the logical array operators AND, OR, and NOT. Short-circuit logical operators allow short-circuiting on logical operations. The symbols && and || are the logical short-circuit operators AND and OR. Show Examples Bitwise Operations Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows − p q p & q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1 Assume if A = 60; and B = 13; Now in binary format they will be as follows − A = 0011 1100 B = 0000 1101 —————– A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A  = 1100 0011 MATLAB provides various functions for bit-wise operations like ”bitwise and”, ”bitwise or” and ”bitwise not” operations, shift operation, etc. The following table shows the commonly used bitwise operations − Show Examples Function Purpose bitand(a, b) Bit-wise AND of integers a and b bitcmp(a) Bit-wise complement of a bitget(a,pos) Get bit at specified position pos, in the integer array a bitor(a, b) Bit-wise OR of integers a and b bitset(a, pos) Set bit at specific location pos of a bitshift(a, k) Returns a shifted to the left by k bits, equivalent to multiplying by 2k. Negative values of k correspond to shifting bits right or dividing by 2|k| and rounding to the nearest integer towards negative infinite. Any overflow bits are truncated. bitxor(a, b) Bit-wise XOR of integers a and b

MATLAB – Vectors

MATLAB – Vectors ”; Previous Next A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors − Row vectors Column vectors Row Vectors Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements. Live Demo r = [7 8 9 10 11] MATLAB will execute the above statement and return the following result − r = 7 8 9 10 11 Column Vectors Column vectors are created by enclosing the set of elements in square brackets, using semicolon to delimit the elements. Live Demo c = [7; 8; 9; 10; 11] MATLAB will execute the above statement and return the following result − c = 7 8 9 10 11 Referencing the Elements of a Vector You can reference one or more of the elements of a vector in several ways. The ith component of a vector v is referred as v(i). For example − Live Demo v = [ 1; 2; 3; 4; 5; 6]; % creating a column vector of 6 elements v(3) MATLAB will execute the above statement and return the following result − ans = 3 When you reference a vector with a colon, such as v(:), all the components of the vector are listed. Live Demo v = [ 1; 2; 3; 4; 5; 6]; % creating a column vector of 6 elements v(:) MATLAB will execute the above statement and return the following result − ans = 1 2 3 4 5 6 MATLAB allows you to select a range of elements from a vector. For example, let us create a row vector rv of 9 elements, then we will reference the elements 3 to 7 by writing rv(3:7) and create a new vector named sub_rv. Live Demo rv = [1 2 3 4 5 6 7 8 9]; sub_rv = rv(3:7) MATLAB will execute the above statement and return the following result − sub_rv = 3 4 5 6 7 Vector Operations In this section, let us discuss the following vector operations − Addition and Subtraction of Vectors Scalar Multiplication of Vectors Transpose of a Vector Appending Vectors Magnitude of a Vector Vector Dot Product Vectors with Uniformly Spaced Elements Print Page Previous Next Advertisements ”;

MATLAB – GNU Octave

MATLAB – GNU Octave Tutorial ”; Previous Next GNU Octave is a high-level programming language like MATLAB and it is mostly compatible with MATLAB. It is also used for numerical computations. Octave has the following common features with MATLAB − matrices are fundamental data type it has built-in support for complex numbers it has built-in math functions and libraries it supports user-defined functions GNU Octave is also freely redistributable software. You may redistribute it and/or modify it under the terms of the GNU General Public License (GPL) as published by the Free Software Foundation. MATLAB vs Octave Most MATLAB programs run in Octave, but some of the Octave programs may not run in MATLAB because, Octave allows some syntax that MATLAB does not. For example, MATLAB supports single quotes only, but Octave supports both single and double quotes for defining strings. If you are looking for a tutorial on Octave, then kindly go through this tutorial from beginning which covers both MATLAB as well as Octave. Compatible Examples Almost all the examples covered in this tutorial are compatible with MATLAB as well as Octave. Let”s try following example in MATLAB and Octave which produces same result without any syntax changes − This example creates a 3D surface map for the function g = xe-(x2 + y2). Create a script file and type the following code − [x,y] = meshgrid(-2:.2:2); g = x .* exp(-x.^2 – y.^2); surf(x, y, g) print -deps graph.eps When you run the file, MATLAB displays the following 3-D map − Non-compatible Examples Though all the core functionality of MATLAB is available in Octave, there are some functionality for example, Differential & Integration Calculus, which does not match exactly in both the languages. This tutorial has tried to give both type of examples where they differed in their syntax. Consider following example where MATLAB and Octave make use of different functions to get the area of a curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9. Following is MATLAB version of the code − f = x^2*cos(x); ezplot(f, [-4,9]) a = int(f, -4, 9) disp(”Area: ”), disp(double(a)); When you run the file, MATLAB plots the graph − The following result is displayed a = 8*cos(4) + 18*cos(9) + 14*sin(4) + 79*sin(9) Area: 0.3326 But to give area of the same curve in Octave, you will have to make use of symbolic package as follows − pkg load symbolic symbols x = sym(“x”); f = inline(“x^2*cos(x)”); ezplot(f, [-4,9]) print -deps graph.eps [a, ierror, nfneval] = quad(f, -4, 9); display(”Area: ”), disp(double(a)); Print Page Previous Next Advertisements ”;

MATLAB – Polynomials

MATLAB – Polynomials ”; Previous Next MATLAB represents polynomials as row vectors containing coefficients ordered by descending powers. For example, the equation P(x) = x4 + 7×3 – 5x + 9 could be represented as − p = [1 7 0 -5 9]; Evaluating Polynomials The polyval function is used for evaluating a polynomial at a specified value. For example, to evaluate our previous polynomial p, at x = 4, type − Live Demo p = [1 7 0 -5 9]; polyval(p,4) MATLAB executes the above statements and returns the following result − ans = 693 MATLAB also provides the polyvalm function for evaluating a matrix polynomial. A matrix polynomial is a polynomial with matrices as variables. For example, let us create a square matrix X and evaluate the polynomial p, at X − Live Demo p = [1 7 0 -5 9]; X = [1 2 -3 4; 2 -5 6 3; 3 1 0 2; 5 -7 3 8]; polyvalm(p, X) MATLAB executes the above statements and returns the following result − ans = 2307 -1769 -939 4499 2314 -2376 -249 4695 2256 -1892 -549 4310 4570 -4532 -1062 9269 Finding the Roots of Polynomials The roots function calculates the roots of a polynomial. For example, to calculate the roots of our polynomial p, type − Live Demo p = [1 7 0 -5 9]; r = roots(p) MATLAB executes the above statements and returns the following result − r = -6.8661 + 0.0000i -1.4247 + 0.0000i 0.6454 + 0.7095i 0.6454 – 0.7095i The function poly is an inverse of the roots function and returns to the polynomial coefficients. For example − p2 = poly(r) MATLAB executes the above statements and returns the following result − p2 = Columns 1 through 3: 1.00000 + 0.00000i 7.00000 + 0.00000i 0.00000 + 0.00000i Columns 4 and 5: -5.00000 – 0.00000i 9.00000 + 0.00000i Polynomial Curve Fitting The polyfit function finds the coefficients of a polynomial that fits a set of data in a least-squares sense. If x and y are two vectors containing the x and y data to be fitted to a n-degree polynomial, then we get the polynomial fitting the data by writing − p = polyfit(x,y,n) Example Create a script file and type the following code − Live Demo x = [1 2 3 4 5 6]; y = [5.5 43.1 128 290.7 498.4 978.67]; %data p = polyfit(x,y,4) %get the polynomial % Compute the values of the polyfit estimate over a finer range, % and plot the estimate over the real data values for comparison: x2 = 1:.1:6; y2 = polyval(p,x2); plot(x,y,”o”,x2,y2) grid on When you run the file, MATLAB displays the following result − p = 4.1056 -47.9607 222.2598 -362.7453 191.1250 And plots the following graph − Print Page Previous Next Advertisements ”;

MATLAB – Differential

MATLAB – Differential ”; Previous Next MATLAB provides the diff command for computing symbolic derivatives. In its simplest form, you pass the function you want to differentiate to diff command as an argument. For example, let us compute the derivative of the function f(t) = 3t2 + 2t-2 Example Create a script file and type the following code into it − syms t f = 3*t^2 + 2*t^(-2); diff(f) When the above code is compiled and executed, it produces the following result − ans = 6*t – 4/t^3 Following is Octave equivalent of the above calculation − pkg load symbolic symbols t = sym(“t”); f = 3*t^2 + 2*t^(-2); differentiate(f,t) Octave executes the code and returns the following result − ans = -(4.0)*t^(-3.0)+(6.0)*t Verification of Elementary Rules of Differentiation Let us briefly state various equations or rules for differentiation of functions and verify these rules. For this purpose, we will write f”(x) for a first order derivative and f”(x) for a second order derivative. Following are the rules for differentiation − Rule 1 For any functions f and g and any real numbers a and b are the derivative of the function − h(x) = af(x) + bg(x) with respect to x is given by − h”(x) = af”(x) + bg”(x) Rule 2 The sum and subtraction rules state that if f and g are two functions, f” and g” are their derivatives respectively, then, (f + g)” = f” + g” (f – g)” = f” – g” Rule 3 The product rule states that if f and g are two functions, f” and g” are their derivatives respectively, then, (f.g)” = f”.g + g”.f Rule 4 The quotient rule states that if f and g are two functions, f” and g” are their derivatives respectively, then, (f/g)” = (f”.g – g”.f)/g2 Rule 5 The polynomial or elementary power rule states that, if y = f(x) = xn, then f” = n. x(n-1) A direct outcome of this rule is that the derivative of any constant is zero, i.e., if y = k, any constant, then f” = 0 Rule 6 The chain rule states that, derivative of the function of a function h(x) = f(g(x)) with respect to x is, h”(x)= f”(g(x)).g”(x) Example Create a script file and type the following code into it − syms x syms t f = (x + 2)*(x^2 + 3) der1 = diff(f) f = (t^2 + 3)*(sqrt(t) + t^3) der2 = diff(f) f = (x^2 – 2*x + 1)*(3*x^3 – 5*x^2 + 2) der3 = diff(f) f = (2*x^2 + 3*x)/(x^3 + 1) der4 = diff(f) f = (x^2 + 1)^17 der5 = diff(f) f = (t^3 + 3* t^2 + 5*t -9)^(-6) der6 = diff(f) When you run the file, MATLAB displays the following result − f = (x^2 + 3)*(x + 2) der1 = 2*x*(x + 2) + x^2 + 3 f = (t^(1/2) + t^3)*(t^2 + 3) der2 = (t^2 + 3)*(3*t^2 + 1/(2*t^(1/2))) + 2*t*(t^(1/2) + t^3) f = (x^2 – 2*x + 1)*(3*x^3 – 5*x^2 + 2) der3 = (2*x – 2)*(3*x^3 – 5*x^2 + 2) – (- 9*x^2 + 10*x)*(x^2 – 2*x + 1) f = (2*x^2 + 3*x)/(x^3 + 1) der4 = (4*x + 3)/(x^3 + 1) – (3*x^2*(2*x^2 + 3*x))/(x^3 + 1)^2 f = (x^2 + 1)^17 der5 = 34*x*(x^2 + 1)^16 f = 1/(t^3 + 3*t^2 + 5*t – 9)^6 der6 = -(6*(3*t^2 + 6*t + 5))/(t^3 + 3*t^2 + 5*t – 9)^7 Following is Octave equivalent of the above calculation − pkg load symbolic symbols x = sym(“x”); t = sym(“t”); f = (x + 2)*(x^2 + 3) der1 = differentiate(f,x) f = (t^2 + 3)*(t^(1/2) + t^3) der2 = differentiate(f,t) f = (x^2 – 2*x + 1)*(3*x^3 – 5*x^2 + 2) der3 = differentiate(f,x) f = (2*x^2 + 3*x)/(x^3 + 1) der4 = differentiate(f,x) f = (x^2 + 1)^17 der5 = differentiate(f,x) f = (t^3 + 3* t^2 + 5*t -9)^(-6) der6 = differentiate(f,t) Octave executes the code and returns the following result − f = (2.0+x)*(3.0+x^(2.0)) der1 = 3.0+x^(2.0)+(2.0)*(2.0+x)*x f = (t^(3.0)+sqrt(t))*(3.0+t^(2.0)) der2 = (2.0)*(t^(3.0)+sqrt(t))*t+((3.0)*t^(2.0)+(0.5)*t^(-0.5))*(3.0+t^(2.0)) f = (1.0+x^(2.0)-(2.0)*x)*(2.0-(5.0)*x^(2.0)+(3.0)*x^(3.0)) der3 = (-2.0+(2.0)*x)*(2.0-(5.0)*x^(2.0)+(3.0)*x^(3.0))+((9.0)*x^(2.0)-(10.0)*x)*(1.0+x^(2.0)-(2.0)*x) f = (1.0+x^(3.0))^(-1)*((2.0)*x^(2.0)+(3.0)*x) der4 = (1.0+x^(3.0))^(-1)*(3.0+(4.0)*x)-(3.0)*(1.0+x^(3.0))^(-2)*x^(2.0)*((2.0)*x^(2.0)+(3.0)*x) f = (1.0+x^(2.0))^(17.0) der5 = (34.0)*(1.0+x^(2.0))^(16.0)*x f = (-9.0+(3.0)*t^(2.0)+t^(3.0)+(5.0)*t)^(-6.0) der6 = -(6.0)*(-9.0+(3.0)*t^(2.0)+t^(3.0)+(5.0)*t)^(-7.0)*(5.0+(3.0)*t^(2.0)+(6.0)*t) Derivatives of Exponential, Logarithmic and Trigonometric Functions The following table provides the derivatives of commonly used exponential, logarithmic and trigonometric functions − Function Derivative ca.x ca.x.ln c.a (ln is natural logarithm) ex ex ln x 1/x lncx 1/x.ln c xx xx.(1 + ln x) sin(x) cos(x) cos(x) -sin(x) tan(x) sec2(x), or 1/cos2(x), or 1 + tan2(x) cot(x) -csc2(x), or -1/sin2(x), or -(1 + cot2(x)) sec(x) sec(x).tan(x) csc(x) -csc(x).cot(x) Example Create a script file and type the following code into it − syms x y = exp(x) diff(y) y = x^9 diff(y) y = sin(x) diff(y) y = tan(x) diff(y) y = cos(x) diff(y) y = log(x) diff(y) y = log10(x) diff(y) y = sin(x)^2 diff(y) y = cos(3*x^2 + 2*x + 1) diff(y) y = exp(x)/sin(x) diff(y) When you run the file, MATLAB displays the following result − y = exp(x) ans = exp(x) y = x^9 ans = 9*x^8 y = sin(x) ans = cos(x) y = tan(x) ans = tan(x)^2 + 1 y = cos(x) ans = -sin(x) y = log(x) ans = 1/x y = log(x)/log(10) ans = 1/(x*log(10)) y = sin(x)^2 ans = 2*cos(x)*sin(x) y = cos(3*x^2 + 2*x + 1) ans = -sin(3*x^2 + 2*x + 1)*(6*x + 2) y = exp(x)/sin(x) ans = exp(x)/sin(x) – (exp(x)*cos(x))/sin(x)^2 Following is Octave equivalent of the above calculation − pkg load symbolic symbols x = sym(“x”); y = Exp(x) differentiate(y,x) y = x^9 differentiate(y,x) y = Sin(x) differentiate(y,x) y = Tan(x) differentiate(y,x) y = Cos(x) differentiate(y,x) y = Log(x) differentiate(y,x) % symbolic packages does not have this support %y = Log10(x) %differentiate(y,x) y = Sin(x)^2 differentiate(y,x) y = Cos(3*x^2 + 2*x + 1) differentiate(y,x) y = Exp(x)/Sin(x) differentiate(y,x) Octave executes the code and returns