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
Category: matlab
MATLAB – Numbers
MATLAB – Numbers ”; Previous Next MATLAB supports various numeric classes that include signed and unsigned integers and single-precision and double-precision floating-point numbers. By default, MATLAB stores all numeric values as double-precision floating point numbers. You can choose to store any number or array of numbers as integers or as single-precision numbers. All numeric types support basic array operations and mathematical operations. Conversion to Various Numeric Data Types MATLAB provides the following functions to convert to various numeric data types − Function Purpose double Converts to double precision number single Converts to single precision number int8 Converts to 8-bit signed integer int16 Converts to 16-bit signed integer int32 Converts to 32-bit signed integer int64 Converts to 64-bit signed integer uint8 Converts to 8-bit unsigned integer uint16 Converts to 16-bit unsigned integer uint32 Converts to 32-bit unsigned integer uint64 Converts to 64-bit unsigned integer Example Create a script file and type the following code − Live Demo x = single([5.32 3.47 6.28]) .* 7.5 x = double([5.32 3.47 6.28]) .* 7.5 x = int8([5.32 3.47 6.28]) .* 7.5 x = int16([5.32 3.47 6.28]) .* 7.5 x = int32([5.32 3.47 6.28]) .* 7.5 x = int64([5.32 3.47 6.28]) .* 7.5 When you run the file, it shows the following result − x = 39.900 26.025 47.100 x = 39.900 26.025 47.100 x = 38 23 45 x = 38 23 45 x = 38 23 45 x = 38 23 45 Example Let us extend the previous example a little more. Create a script file and type the following code − Live Demo x = int32([5.32 3.47 6.28]) .* 7.5 x = int64([5.32 3.47 6.28]) .* 7.5 x = num2cell(x) When you run the file, it shows the following result − x = 38 23 45 x = 38 23 45 x = { [1,1] = 38 [1,2] = 23 [1,3] = 45 } Smallest and Largest Integers The functions intmax() and intmin() return the maximum and minimum values that can be represented with all types of integer numbers. Both the functions take the integer data type as the argument, for example, intmax(int8) or intmin(int64) and return the maximum and minimum values that you can represent with the integer data type. Example The following example illustrates how to obtain the smallest and largest values of integers. Create a script file and write the following code in it − Live Demo % displaying the smallest and largest signed integer data str = ”The range for int8 is:nt%d to %d ”; sprintf(str, intmin(”int8”), intmax(”int8”)) str = ”The range for int16 is:nt%d to %d ”; sprintf(str, intmin(”int16”), intmax(”int16”)) str = ”The range for int32 is:nt%d to %d ”; sprintf(str, intmin(”int32”), intmax(”int32”)) str = ”The range for int64 is:nt%d to %d ”; sprintf(str, intmin(”int64”), intmax(”int64”)) % displaying the smallest and largest unsigned integer data str = ”The range for uint8 is:nt%d to %d ”; sprintf(str, intmin(”uint8”), intmax(”uint8”)) str = ”The range for uint16 is:nt%d to %d ”; sprintf(str, intmin(”uint16”), intmax(”uint16”)) str = ”The range for uint32 is:nt%d to %d ”; sprintf(str, intmin(”uint32”), intmax(”uint32”)) str = ”The range for uint64 is:nt%d to %d ”; sprintf(str, intmin(”uint64”), intmax(”uint64”)) When you run the file, it shows the following result − ans = The range for int8 is: -128 to 127 ans = The range for int16 is: -32768 to 32767 ans = The range for int32 is: -2147483648 to 2147483647 ans = The range for int64 is: 0 to 0 ans = The range for uint8 is: 0 to 255 ans = The range for uint16 is: 0 to 65535 ans = The range for uint32 is: 0 to -1 ans = The range for uint64 is: 0 to 18446744073709551616 Smallest and Largest Floating Point Numbers The functions realmax() and realmin() return the maximum and minimum values that can be represented with floating point numbers. Both the functions when called with the argument ”single”, return the maximum and minimum values that you can represent with the single-precision data type and when called with the argument ”double”, return the maximum and minimum values that you can represent with the double-precision data type. Example The following example illustrates how to obtain the smallest and largest floating point numbers. Create a script file and write the following code in it − Live Demo % displaying the smallest and largest single-precision % floating point number str = ”The range for single is:nt%g to %g andnt %g to %g”; sprintf(str, -realmax(”single”), -realmin(”single”), … realmin(”single”), realmax(”single”)) % displaying the smallest and largest double-precision % floating point number str = ”The range for double is:nt%g to %g andnt %g to %g”; sprintf(str, -realmax(”double”), -realmin(”double”), … realmin(”double”), realmax(”double”)) When you run the file, it displays the following result − ans = The range for single is: -3.40282e+38 to -1.17549e-38 and 1.17549e-38 to 3.40282e+38 ans = The range for double is: -1.79769e+308 to -2.22507e-308 and 2.22507e-308 to 1.79769e+308 Print Page Previous Next Advertisements ”;
MATLAB – Transforms
MATLAB – Transforms ”; Previous Next MATLAB provides command for working with transforms, such as the Laplace and Fourier transforms. Transforms are used in science and engineering as a tool for simplifying analysis and look at data from another angle. For example, the Fourier transform allows us to convert a signal represented as a function of time to a function of frequency. Laplace transform allows us to convert a differential equation to an algebraic equation. MATLAB provides the laplace, fourier and fft commands to work with Laplace, Fourier and Fast Fourier transforms. The Laplace Transform The Laplace transform of a function of time f(t) is given by the following integral − Laplace transform is also denoted as transform of f(t) to F(s). You can see this transform or integration process converts f(t), a function of the symbolic variable t, into another function F(s), with another variable s. Laplace transform turns differential equations into algebraic ones. To compute a Laplace transform of a function f(t), write − laplace(f(t)) Example In this example, we will compute the Laplace transform of some commonly used functions. Create a script file and type the following code − syms s t a b w laplace(a) laplace(t^2) laplace(t^9) laplace(exp(-b*t)) laplace(sin(w*t)) laplace(cos(w*t)) When you run the file, it displays the following result − ans = 1/s^2 ans = 2/s^3 ans = 362880/s^10 ans = 1/(b + s) ans = w/(s^2 + w^2) ans = s/(s^2 + w^2) The Inverse Laplace Transform MATLAB allows us to compute the inverse Laplace transform using the command ilaplace. For example, ilaplace(1/s^3) MATLAB will execute the above statement and display the result − ans = t^2/2 Example Create a script file and type the following code − syms s t a b w ilaplace(1/s^7) ilaplace(2/(w+s)) ilaplace(s/(s^2+4)) ilaplace(exp(-b*t)) ilaplace(w/(s^2 + w^2)) ilaplace(s/(s^2 + w^2)) When you run the file, it displays the following result − ans = t^6/720 ans = 2*exp(-t*w) ans = cos(2*t) ans = ilaplace(exp(-b*t), t, x) ans = sin(t*w) ans = cos(t*w) The Fourier Transforms Fourier transforms commonly transforms a mathematical function of time, f(t), into a new function, sometimes denoted by or F, whose argument is frequency with units of cycles/s (hertz) or radians per second. The new function is then known as the Fourier transform and/or the frequency spectrum of the function f. Example Create a script file and type the following code in it − syms x f = exp(-2*x^2); %our function ezplot(f,[-2,2]) % plot of our function FT = fourier(f) % Fourier transform When you run the file, MATLAB plots the following graph − The following result is displayed − FT = (2^(1/2)*pi^(1/2)*exp(-w^2/8))/2 Plotting the Fourier transform as − ezplot(FT) Gives the following graph − Inverse Fourier Transforms MATLAB provides the ifourier command for computing the inverse Fourier transform of a function. For example, f = ifourier(-2*exp(-abs(w))) MATLAB will execute the above statement and display the result − f = -2/(pi*(x^2 + 1)) Print Page Previous Next Advertisements ”;
MATLAB – Integration
MATLAB – Integration ”; Previous Next Integration deals with two essentially different types of problems. In the first type, derivative of a function is given and we want to find the function. Therefore, we basically reverse the process of differentiation. This reverse process is known as anti-differentiation, or finding the primitive function, or finding an indefinite integral. The second type of problems involve adding up a very large number of very small quantities and then taking a limit as the size of the quantities approaches zero, while the number of terms tend to infinity. This process leads to the definition of the definite integral. Definite integrals are used for finding area, volume, center of gravity, moment of inertia, work done by a force, and in numerous other applications. Finding Indefinite Integral Using MATLAB By definition, if the derivative of a function f(x) is f”(x), then we say that an indefinite integral of f”(x) with respect to x is f(x). For example, since the derivative (with respect to x) of x2 is 2x, we can say that an indefinite integral of 2x is x2. In symbols − f”(x2) = 2x, therefore, ∫ 2xdx = x2. Indefinite integral is not unique, because derivative of x2 + c, for any value of a constant c, will also be 2x. This is expressed in symbols as − ∫ 2xdx = x2 + c. Where, c is called an ”arbitrary constant”. MATLAB provides an int command for calculating integral of an expression. To derive an expression for the indefinite integral of a function, we write − int(f); For example, from our previous example − syms x int(2*x) MATLAB executes the above statement and returns the following result − ans = x^2 Example 1 In this example, let us find the integral of some commonly used expressions. Create a script file and type the following code in it − syms x n int(sym(x^n)) f = ”sin(n*t)” int(sym(f)) syms a t int(a*cos(pi*t)) int(a^x) When you run the file, it displays the following result − ans = piecewise([n == -1, log(x)], [n ~= -1, x^(n + 1)/(n + 1)]) f = sin(n*t) ans = -cos(n*t)/n ans = (a*sin(pi*t))/pi ans = a^x/log(a) Example 2 Create a script file and type the following code in it − syms x n int(cos(x)) int(exp(x)) int(log(x)) int(x^-1) int(x^5*cos(5*x)) pretty(int(x^5*cos(5*x))) int(x^-5) int(sec(x)^2) pretty(int(1 – 10*x + 9 * x^2)) int((3 + 5*x -6*x^2 – 7*x^3)/2*x^2) pretty(int((3 + 5*x -6*x^2 – 7*x^3)/2*x^2)) Note that the pretty function returns an expression in a more readable format. When you run the file, it displays the following result − ans = sin(x) ans = exp(x) ans = x*(log(x) – 1) ans = log(x) ans = (24*cos(5*x))/3125 + (24*x*sin(5*x))/625 – (12*x^2*cos(5*x))/125 + (x^4*cos(5*x))/5 – (4*x^3*sin(5*x))/25 + (x^5*sin(5*x))/5 2 4 24 cos(5 x) 24 x sin(5 x) 12 x cos(5 x) x cos(5 x) ———– + ————- – ————– + ———— 3125 625 125 5 3 5 4 x sin(5 x) x sin(5 x) ————- + ———– 25 5 ans = -1/(4*x^4) ans = tan(x) 2 x (3 x – 5 x + 1) ans = – (7*x^6)/12 – (3*x^5)/5 + (5*x^4)/8 + x^3/2 6 5 4 3 7 x 3 x 5 x x – —- – —- + —- + — 12 5 8 2 Finding Definite Integral Using MATLAB By definition, definite integral is basically the limit of a sum. We use definite integrals to find areas such as the area between a curve and the x-axis and the area between two curves. Definite integrals can also be used in other situations, where the quantity required can be expressed as the limit of a sum. The int function can be used for definite integration by passing the limits over which you want to calculate the integral. To calculate we write, int(x, a, b) For example, to calculate the value of we write − int(x, 4, 9) MATLAB executes the above statement and returns the following result − ans = 65/2 Following is Octave equivalent of the above calculation − pkg load symbolic symbols x = sym(“x”); f = x; c = [1, 0]; integral = polyint(c); a = polyval(integral, 9) – polyval(integral, 4); display(”Area: ”), disp(double(a)); Octave executes the code and returns the following result − Area: 32.500 An alternative solution can be given using quad() function provided by Octave as follows − pkg load symbolic symbols f = inline(“x”); [a, ierror, nfneval] = quad(f, 4, 9); display(”Area: ”), disp(double(a)); Octave executes the code and returns the following result − Area: 32.500 Example 1 Let us calculate the area enclosed between the x-axis, and the curve y = x3−2x+5 and the ordinates x = 1 and x = 2. The required area is given by − Create a script file and type the following code − f = x^3 – 2*x +5; a = int(f, 1, 2) display(”Area: ”), disp(double(a)); When you run the file, it displays the following result − a = 23/4 Area: 5.7500 Following is Octave equivalent of the above calculation − pkg load symbolic symbols x = sym(“x”); f = x^3 – 2*x +5; c = [1, 0, -2, 5]; integral = polyint(c); a = polyval(integral, 2) – polyval(integral, 1); display(”Area: ”), disp(double(a)); Octave executes the code and returns the following result − Area: 5.7500 An alternative solution can be given using quad() function provided by Octave as follows − pkg load symbolic symbols x = sym(“x”); f = inline(“x^3 – 2*x +5″); [a, ierror, nfneval] = quad(f, 1, 2); display(”Area: ”), disp(double(a)); Octave executes the code and returns the following result − Area: 5.7500 Example 2 Find the area under the curve: f(x) = x2 cos(x) for −4 ≤ x ≤ 9. Create a script file and write the following 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 output is given below − a = 8*cos(4) + 18*cos(9) + 14*sin(4)
MATLAB – Data Output
MATLAB – Data Output ”; Previous Next Data export (or output) in MATLAB means to write into files. MATLAB allows you to use your data in another application that reads ASCII files. For this, MATLAB provides several data export options. You can create the following type of files − Rectangular, delimited ASCII data file from an array. Diary (or log) file of keystrokes and the resulting text output. Specialized ASCII file using low-level functions such as fprintf. MEX-file to access your C/C++ or Fortran routine that writes to a particular text file format. Apart from this, you can also export data to spreadsheets. There are two ways to export a numeric array as a delimited ASCII data file − Using the save function and specifying the -ascii qualifier Using the dlmwrite function Syntax for using the save function is − save my_data.out num_array -ascii where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and −ascii is the specifier. Syntax for using the dlmwrite function is − dlmwrite(”my_data.out”, num_array, ”dlm_char”) where, my_data.out is the delimited ASCII data file created, num_array is a numeric array and dlm_char is the delimiter character. Example The following example demonstrates the concept. Create a script file and type the following code − Live Demo num_array = [ 1 2 3 4 ; 4 5 6 7; 7 8 9 0]; save array_data1.out num_array -ascii; type array_data1.out dlmwrite(”array_data2.out”, num_array, ” ”); type array_data2.out When you run the file, it displays the following result − 1.0000000e+00 2.0000000e+00 3.0000000e+00 4.0000000e+00 4.0000000e+00 5.0000000e+00 6.0000000e+00 7.0000000e+00 7.0000000e+00 8.0000000e+00 9.0000000e+00 0.0000000e+00 1 2 3 4 4 5 6 7 7 8 9 0 Please note that the save -ascii command and the dlmwrite function does not work with cell arrays as input. To create a delimited ASCII file from the contents of a cell array, you can Either, convert the cell array to a matrix using the cell2mat function Or export the cell array using low-level file I/O functions. If you use the save function to write a character array to an ASCII file, it writes the ASCII equivalent of the characters to the file. For example, let us write the word ”hello” to a file − Live Demo h = ”hello”; save textdata.out h -ascii type textdata.out MATLAB executes the above statements and displays the following result. which is the characters of the string ”hello” in 8-digit ASCII format. 1.0400000e+02 1.0100000e+02 1.0800000e+02 1.0800000e+02 1.1100000e+02 Writing to Diary Files Diary files are activity logs of your MATLAB session. The diary function creates an exact copy of your session in a disk file, excluding graphics. To turn on the diary function, type − diary Optionally, you can give the name of the log file, say − diary logdata.out To turn off the diary function − diary off You can open the diary file in a text editor. Exporting Data to Text Data Files with Low-Level I/O So far, we have exported numeric arrays. However, you may need to create other text files, including combinations of numeric and character data, nonrectangular output files, or files with non-ASCII encoding schemes. For these purposes, MATLAB provides the low-level fprintf function. As in low-level I/O file activities, before exporting, you need to open or create a file with the fopen function and get the file identifier. By default, fopen opens a file for read-only access. You should specify the permission to write or append, such as ”w” or ”a”. After processing the file, you need to close it with fclose(fid) function. The following example demonstrates the concept − Example Create a script file and type the following code in it − Live Demo % create a matrix y, with two rows x = 0:10:100; y = [x; log(x)]; % open a file for writing fid = fopen(”logtable.txt”, ”w”); % Table Header fprintf(fid, ”Log Functionnn”); % print values in column order % two values appear on each row of the file fprintf(fid, ”%f %fn”, y); fclose(fid); % display the file created type logtable.txt When you run the file, it displays the following result − Log Function 0.000000 -Inf 10.000000 2.302585 20.000000 2.995732 30.000000 3.401197 40.000000 3.688879 50.000000 3.912023 60.000000 4.094345 70.000000 4.248495 80.000000 4.382027 90.000000 4.499810 100.000000 4.605170 Print Page Previous Next Advertisements ”;
MATLAB – Algebra
MATLAB – Algebra ”; Previous Next So far, we have seen that all the examples work in MATLAB as well as its GNU, alternatively called Octave. But for solving basic algebraic equations, both MATLAB and Octave are little different, so we will try to cover MATLAB and Octave in separate sections. We will also discuss factorizing and simplification of algebraic expressions. Solving Basic Algebraic Equations in MATLAB The solve function is used for solving algebraic equations. In its simplest form, the solve function takes the equation enclosed in quotes as an argument. For example, let us solve for x in the equation x-5 = 0 solve(”x-5=0”) MATLAB will execute the above statement and return the following result − ans = 5 You can also call the solve function as − y = solve(”x-5 = 0”) MATLAB will execute the above statement and return the following result − y = 5 You may even not include the right hand side of the equation − solve(”x-5”) MATLAB will execute the above statement and return the following result − ans = 5 If the equation involves multiple symbols, then MATLAB by default assumes that you are solving for x, however, the solve function has another form − solve(equation, variable) where, you can also mention the variable. For example, let us solve the equation v – u – 3t2 = 0, for v. In this case, we should write − solve(”v-u-3*t^2=0”, ”v”) MATLAB will execute the above statement and return the following result − ans = 3*t^2 + u Solving Basic Algebraic Equations in Octave The roots function is used for solving algebraic equations in Octave and you can write above examples as follows − For example, let us solve for x in the equation x-5 = 0 Live Demo roots([1, -5]) Octave will execute the above statement and return the following result − ans = 5 You can also call the solve function as − Live Demo y = roots([1, -5]) Octave will execute the above statement and return the following result − y = 5 Solving Quadratic Equations in MATLAB The solve function can also solve higher order equations. It is often used to solve quadratic equations. The function returns the roots of the equation in an array. The following example solves the quadratic equation x2 -7x +12 = 0. Create a script file and type the following code − eq = ”x^2 -7*x + 12 = 0”; s = solve(eq); disp(”The first root is: ”), disp(s(1)); disp(”The second root is: ”), disp(s(2)); When you run the file, it displays the following result − The first root is: 3 The second root is: 4 Solving Quadratic Equations in Octave The following example solves the quadratic equation x2 -7x +12 = 0 in Octave. Create a script file and type the following code − Live Demo s = roots([1, -7, 12]); disp(”The first root is: ”), disp(s(1)); disp(”The second root is: ”), disp(s(2)); When you run the file, it displays the following result − The first root is: 4 The second root is: 3 Solving Higher Order Equations in MATLAB The solve function can also solve higher order equations. For example, let us solve a cubic equation as (x-3)2(x-7) = 0 solve(”(x-3)^2*(x-7)=0”) MATLAB will execute the above statement and return the following result − ans = 3 3 7 In case of higher order equations, roots are long containing many terms. You can get the numerical value of such roots by converting them to double. The following example solves the fourth order equation x4 − 7×3 + 3×2 − 5x + 9 = 0. Create a script file and type the following code − eq = ”x^4 – 7*x^3 + 3*x^2 – 5*x + 9 = 0”; s = solve(eq); disp(”The first root is: ”), disp(s(1)); disp(”The second root is: ”), disp(s(2)); disp(”The third root is: ”), disp(s(3)); disp(”The fourth root is: ”), disp(s(4)); % converting the roots to double type disp(”Numeric value of first root”), disp(double(s(1))); disp(”Numeric value of second root”), disp(double(s(2))); disp(”Numeric value of third root”), disp(double(s(3))); disp(”Numeric value of fourth root”), disp(double(s(4))); When you run the file, it returns the following result − The first root is: 6.630396332390718431485053218985 The second root is: 1.0597804633025896291682772499885 The third root is: – 0.34508839784665403032666523448675 – 1.0778362954630176596831109269793*i The fourth root is: – 0.34508839784665403032666523448675 + 1.0778362954630176596831109269793*i Numeric value of first root 6.6304 Numeric value of second root 1.0598 Numeric value of third root -0.3451 – 1.0778i Numeric value of fourth root -0.3451 + 1.0778i Please note that the last two roots are complex numbers. Solving Higher Order Equations in Octave The following example solves the fourth order equation x4 − 7×3 + 3×2 − 5x + 9 = 0. Create a script file and type the following code − Live Demo v = [1, -7, 3, -5, 9]; s = roots(v); % converting the roots to double type disp(”Numeric value of first root”), disp(double(s(1))); disp(”Numeric value of second root”), disp(double(s(2))); disp(”Numeric value of third root”), disp(double(s(3))); disp(”Numeric value of fourth root”), disp(double(s(4))); When you run the file, it returns the following result − Numeric value of first root 6.6304 Numeric value of second root -0.34509 + 1.07784i Numeric value of third root -0.34509 – 1.07784i Numeric value of fourth root 1.0598 Solving System of Equations in MATLAB The solve function can also be used to generate solutions of systems of equations involving more than one variables. Let us take up a simple example to demonstrate this use. Let us solve the equations − 5x + 9y = 5 3x – 6y = 4 Create a script file and type the following code − s = solve(”5*x + 9*y = 5”,”3*x – 6*y = 4”); s.x s.y When you run the file, it displays the following result − ans = 22/19 ans = -5/57 In same way, you can solve larger linear systems. Consider the following set of equations − x + 3y -2z = 5 3x + 5y + 6z = 7 2x
MATLAB – Graphics
MATLAB – Graphics ”; Previous Next This chapter will continue exploring the plotting and graphics capabilities of MATLAB. We will discuss − Drawing bar charts Drawing contours Three dimensional plots Drawing Bar Charts The bar command draws a two dimensional bar chart. Let us take up an example to demonstrate the idea. Example Let us have an imaginary classroom with 10 students. We know the percent of marks obtained by these students are 75, 58, 90, 87, 50, 85, 92, 75, 60 and 95. We will draw the bar chart for this data. Create a script file and type the following code − x = [1:10]; y = [75, 58, 90, 87, 50, 85, 92, 75, 60, 95]; bar(x,y), xlabel(”Student”),ylabel(”Score”), title(”First Sem:”) print -deps graph.eps When you run the file, MATLAB displays the following bar chart − Drawing Contours A contour line of a function of two variables is a curve along which the function has a constant value. Contour lines are used for creating contour maps by joining points of equal elevation above a given level, such as mean sea level. MATLAB provides a contour function for drawing contour maps. Example Let us generate a contour map that shows the contour lines for a given function g = f(x, y). This function has two variables. So, we will have to generate two independent variables, i.e., two data sets x and y. This is done by calling the meshgrid command. The meshgrid command is used for generating a matrix of elements that give the range over x and y along with the specification of increment in each case. Let us plot our function g = f(x, y), where −5 ≤ x ≤ 5, −3 ≤ y ≤ 3. Let us take an increment of 0.1 for both the values. The variables are set as − [x,y] = meshgrid(–5:0.1:5, –3:0.1:3); Lastly, we need to assign the function. Let our function be: x2 + y2 Create a script file and type the following code − [x,y] = meshgrid(-5:0.1:5,-3:0.1:3); %independent variables g = x.^2 + y.^2; % our function contour(x,y,g) % call the contour function print -deps graph.eps When you run the file, MATLAB displays the following contour map − Let us modify the code a little to spruce up the map [x,y] = meshgrid(-5:0.1:5,-3:0.1:3); %independent variables g = x.^2 + y.^2; % our function [C, h] = contour(x,y,g); % call the contour function set(h,”ShowText”,”on”,”TextStep”,get(h,”LevelStep”)*2) print -deps graph.eps When you run the file, MATLAB displays the following contour map − Three Dimensional Plots Three-dimensional plots basically display a surface defined by a function in two variables, g = f (x,y). As before, to define g, we first create a set of (x,y) points over the domain of the function using the meshgrid command. Next, we assign the function itself. Finally, we use the surf command to create a surface plot. The following example demonstrates the concept − Example Let us create 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 − You can also use the mesh command to generate a three-dimensional surface. However, the surf command displays both the connecting lines and the faces of the surface in color, whereas, the mesh command creates a wireframe surface with colored lines connecting the defining points. Print Page Previous Next Advertisements ”;
MATLAB – Functions
MATLAB – Functions ”; Previous Next A function is a group of statements that together perform a task. In MATLAB, functions are defined in separate files. The name of the file and of the function should be the same. Functions operate on variables within their own workspace, which is also called the local workspace, separate from the workspace you access at the MATLAB command prompt which is called the base workspace. Functions can accept more than one input arguments and may return more than one output arguments. Syntax of a function statement is − function [out1,out2, …, outN] = myfun(in1,in2,in3, …, inN) Example The following function named mymax should be written in a file named mymax.m. It takes five numbers as argument and returns the maximum of the numbers. Create a function file, named mymax.m and type the following code in it − function max = mymax(n1, n2, n3, n4, n5) %This function calculates the maximum of the % five numbers given as input max = n1; if(n2 > max) max = n2; end if(n3 > max) max = n3; end if(n4 > max) max = n4; end if(n5 > max) max = n5; end The first line of a function starts with the keyword function. It gives the name of the function and order of arguments. In our example, the mymax function has five input arguments and one output argument. The comment lines that come right after the function statement provide the help text. These lines are printed when you type − help mymax MATLAB will execute the above statement and return the following result − This function calculates the maximum of the five numbers given as input You can call the function as − mymax(34, 78, 89, 23, 11) MATLAB will execute the above statement and return the following result − ans = 89 Anonymous Functions An anonymous function is like an inline function in traditional programming languages, defined within a single MATLAB statement. It consists of a single MATLAB expression and any number of input and output arguments. You can define an anonymous function right at the MATLAB command line or within a function or script. This way you can create simple functions without having to create a file for them. The syntax for creating an anonymous function from an expression is f = @(arglist)expression Example In this example, we will write an anonymous function named power, which will take two numbers as input and return first number raised to the power of the second number. Create a script file and type the following code in it − Live Demo power = @(x, n) x.^n; result1 = power(7, 3) result2 = power(49, 0.5) result3 = power(10, -10) result4 = power (4.5, 1.5) When you run the file, it displays − result1 = 343 result2 = 7 result3 = 1.0000e-10 result4 = 9.5459 Primary and Sub-Functions Any function other than an anonymous function must be defined within a file. Each function file contains a required primary function that appears first and any number of optional sub-functions that comes after the primary function and used by it. Primary functions can be called from outside of the file that defines them, either from command line or from other functions, but sub-functions cannot be called from command line or other functions, outside the function file. Sub-functions are visible only to the primary function and other sub-functions within the function file that defines them. Example Let us write a function named quadratic that would calculate the roots of a quadratic equation. The function would take three inputs, the quadratic co-efficient, the linear co-efficient and the constant term. It would return the roots. The function file quadratic.m will contain the primary function quadratic and the sub-function disc, which calculates the discriminant. Create a function file quadratic.m and type the following code in it − function [x1,x2] = quadratic(a,b,c) %this function returns the roots of % a quadratic equation. % It takes 3 input arguments % which are the co-efficients of x2, x and the %constant term % It returns the roots d = disc(a,b,c); x1 = (-b + d) / (2*a); x2 = (-b – d) / (2*a); end % end of quadratic function dis = disc(a,b,c) %function calculates the discriminant dis = sqrt(b^2 – 4*a*c); end % end of sub-function You can call the above function from command prompt as − quadratic(2,4,-4) MATLAB will execute the above statement and return the following result − ans = 0.7321 Nested Functions You can define functions within the body of another function. These are called nested functions. A nested function contains any or all of the components of any other function. Nested functions are defined within the scope of another function and they share access to the containing function”s workspace. A nested function follows the following syntax − function x = A(p1, p2) … B(p2) function y = B(p3) … end … end Example Let us rewrite the function quadratic, from previous example, however, this time the disc function will be a nested function. Create a function file quadratic2.m and type the following code in it − function [x1,x2] = quadratic2(a,b,c) function disc % nested function d = sqrt(b^2 – 4*a*c); end % end of function disc disc; x1 = (-b + d) / (2*a); x2 = (-b – d) / (2*a); end % end of function quadratic2 You can call the above function from command prompt as − quadratic2(2,4,-4) MATLAB will execute the above statement and return the following result − ans = 0.73205 Private Functions A private function is a primary function that is visible only to a limited group of other functions. If you do not want to expose the implementation of a function(s), you can create them as private functions. Private functions reside in subfolders with the special name private. They are visible only to functions in the parent folder. Example Let us rewrite the quadratic function. This time, however, the disc function calculating the discriminant, will
MATLAB – Loops
MATLAB – Loop Types ”; Previous Next There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially. The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages − MATLAB provides following types of loops to handle looping requirements. Click the following links to check their detail − Sr.No. Loop Type & Description 1 while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 2 for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. 3 nested loops You can use one or more loops inside any another loop. Loop Control Statements Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. MATLAB supports the following control statements. Click the following links to check their detail. Sr.No. Control Statement & Description 1 break statement Terminates the loop statement and transfers execution to the statement immediately following the loop. 2 continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. Print Page Previous Next Advertisements ”;
MATLAB – Decisions
MATLAB – Decision Making ”; Previous Next Decision making structures require that the programmer should specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − MATLAB provides following types of decision making statements. Click the following links to check their detail − Sr.No. Statement & Description 1 if … end statement An if … end statement consists of a boolean expression followed by one or more statements. 2 if…else…end statement An if statement can be followed by an optional else statement, which executes when the boolean expression is false. 3 If… elseif…elseif…else…end statements An if statement can be followed by one (or more) optional elseif… and an else statement, which is very useful to test various conditions. 4 nested if statements You can use one if or elseif statement inside another if or elseif statement(s). 5 switch statement A switch statement allows a variable to be tested for equality against a list of values. 6 nested switch statements You can use one switch statement inside another switch statement(s). Print Page Previous Next Advertisements ”;