CHAPTER 1

image

Symbolic Variables and Functions

1-1. Symbolic Variables

MATLAB deems as symbolic any algebraic expression whose variables have all been previously defined as symbolic; variables are declared as symbolic using the command syms. For example, if we want to treat as symbolic the expression 6 * a * b + 3 * a^2 + 2 * a * b, in order to simplify it, we need to declare the two variables a and b as symbolic, as shown here:

>> syms a b
>> simplify(6*a*b + 3*a^2 + 2*a*b)
ans =

8 * a * b + 3 * a ^ 2

As we will see, the command needed to transform a numeric expression to symbolic is sym. For example, if we want to simplify the numeric expression 2/5 + 6/10 + 8/20, we need to first transform it to a symbolic expression with sym(2/5+6/10+8/20), performing the simplification as follows:

>> simplify(sym(2/5+6/10+8/20))
ans =

7/5

The variables of symbolic expressions must be symbolic. Some of the commands for working with symbolic and numeric variables are detailed below:

  • syms x y z... t makes the variables x, y, z,..., t symbolic.
  • syms x y z... t real converts the variables x, y, z,..., t to symbolic variables with real values.
  • syms x y z... t unreal undoes the previous declaration, so that the variables x, y, z,..., t may now have non-zero imaginary parts.
  • syms lists all symbolic variables currently in the workspace.
  • x = sym('x') declares the variable x as symbolic (equivalent to syms x).
  • x = sym('x', real) converts x to a real symbolic variable.
  • x = sym('x',unreal) enables the symbolic variable x to have non-zero imaginary part.
  • S = sym(A) creates a symbolic object from A, where A may be a string, a scalar, an array, a numeric expression, and so on.
  • S = sym(A,'option') converts the array, scalar or numeric expression to a symbolic expression according to the specified option. The option can be f for floating point, r for rational, e for estimate error, or d for decimal.
  • numeric(x) or double(x) converts the variable or expression x to double-precision.
  • sym2poly(poly) converts the symbolic polynomial poly to a vector whose components are its coefficients.
  • poly2sym(vector) returns a symbolic representation of the polynomial whose coefficients are given by the vector.
  • poly2sym(vector,'v') converts a vector into a symbolic polynomial in the variable v.
  • digits(d) sets the precision of symbolic variables to d significant decimal digits.
  • digits returns the current precision for symbolic variables.
  • vpa(expr) returns the numerical result of the expression with a number of significant decimal digits of precision determined by digits.
  • vpa(expr, n) or vpa('expr', n)  returns the numerical result of the expression to n significant decimal digits.
  • pretty(expr) displays the symbolic expression using standard mathematical formatting.

EXERCISE 1-1

Solve the equation ax2 + bx + c = 0 assuming that the variable is x. Also solve it for the variables a, b and c, respectively.

Because MATLAB considers x to be symbolic by default, we can solve the equation directly for x without having to specify it as a symbolic variable using the command solve (note that in MATLAB the equations are introduced within single quotes):

>> solve('a*x^2+b*x+c=0')

ans =

[1/2/a*(-b+(b^2-4*a*c)^(1/2))]
[1/2/a*(-b-(b^2-4*a*c)^(1/2))]

However, to solve the equation with respect to the variables a, b or c , it is necessary to first declare them as symbolic variables:

>> syms a
>> solve('a*x^2+b*x+c=0',a)

ans =

-(b*x+c)/x^2

>> syms b
>> solve('a*x^2+b*x+c=0',b)

ans =

-(a*x^2+c)/x

>> syms c
>> solve('a*x^2+b*x+c=0',c)

ans =

-a*x^2 - b*x

EXERCISE 1-2

Find the roots of the polynomial x4 - 8 x2 + 16 = 0, obtaining the result to default accuracy, to 20 significant figures and to double-precision exact accuracy. Also generate the vector of coefficients associated with the polynomial.

>> p = solve('x^4-8*x^2-16=0')

p =

[2*(2^(1/2)+1)^(1/2)]
[-2*(2^(1/2)+1)^(1/2)]
[2*(1-2^(1/2))^(1/2)]
[-2*(1-2^(1/2))^(1/2)]

>> vpa(p)

ans =

[    3.1075479480600746146883179061262]
[   -3.1075479480600746146883179061262]
[  1.2871885058111652494708868748364*i]
[-1.2871885058111652494708868748364*i]

>> numeric(p)

ans =

 3.1075
-3.1075
      0 + 1.2872i
      0 - 1.2872i

>> vpa(p,20)

ans =

[   3.1075479480600746146]
[  -3.1075479480600746146]
[1.2871885058111652495*i]
[-1.2871885058111652495*i]

>>  syms x
>>  sym2poly(x^4-8*x^2-16)

ans =

1 0 -8 0 -16

EXERCISE 1-3

Find the numerical value, to default precision, of the abscissa of the intersection of the curves y = sin(x) and y = cos(x) in the first quadrant. Find the exact (symbolic) solution. Find the abscissa to a precision of 12 decimal places.

>> p = numeric(solve('sin(x) = cos(x)'))

p =

0.7854

>> q = sym (p)

q =

PI/4

>> digits(12); r=numeric(solve('sin(x)=cos(x)'))

r =

.785398163398

EXERCISE 1-4

Simplify the following expressions as much as possible:

1/2m - 1/3m + 1/4m + 1/5m + 1/6m

1/2 - 1/3 + 1/4 + 1/5 + 1/6

>> syms m
>> simplify(1/(2*m) - 1/(3*m) + 1/(4*m) + 1/(5*m) + 1/(6*m))

ans =

47/60/m

>> pretty(simplify(1/(2*m) - 1/(3*m) + 1/(4*m) + 1/(5*m) + 1/(6*m)))

47
--
60

>> sym(1/2 - 1/3 + 1/4 + 1/5 + 1/6)

ans =

47/60

1-2. Symbolic Vector Variables

A variable that represents a vector of length n can be defined in MATLAB in the following ways:

variable = [e1, e2, e3,..., en]
variable = [e1 e2 e3... en]

Therefore, to define a vector variable, simply insert brackets around the vector elements, separated by commas or blank spaces.

On the other hand, you can also define symbolic vector variables, after previously using the syms command.

>> syms t
>> A=sym([sin(t),cos(t)])
A =

[sin (t), cos (t)]

1-3. Symbolic Matrix Variables

To define an array in MATLAB, simply enter in brackets all of its row vectors separated by semicolons. When entering a vector, you can separate its components by spaces or commas, as we’ve already seen. For example, a 3 × 3 matrix variable can be entered in the following two ways:

matrix = [a11 a12 a13;a21 a22 a23;a31 a32 a33]

matrix = [a11, a12, a13;a21, a22, a23;a31, a32, a33]

We would similarly define an M × N variable array. To work with symbolic matrices, we simply declare the variables involved to be symbolic with the syms command:

>> syms t
>>  A=sym([sin(t),cos(t);tan(t),exp(t)])
A =

[sin (t), cos (t)]
[tan (t), exp (t)]
>> b = inv (A)
b =

[-exp (t) / (-sin (t) * exp (t) + cos (t) * tan (t)), cos (t) / (-sin (t) * exp (t) + cos (t) * tan (t))]
[tan (t) / (-sin (t) * exp (t) + cos (t) * tan (t)), - sin (t) / (-sin (t) * exp (t) + cos (t) * tan (t))]

Once a matrix variable has been defined, MATLAB provides many ways to insert, extract, renumber, and generally manipulate its elements.

  • A(m,n) returns the (m, n)th element of the matrix A (row m and column n).
  • A(a:b,c:d) returns the subarray of A formed by the a-th through b-th rows, inclusive, and the c-th and d-th columns, inclusive.
  • A(a:p:b,c:q:d) returns the subarray of A formed by every p-th row between the a-th and b-th rows and by every q-th column between the c-th and d-th columns.
  • A([a b],[c d]) returns the subarray of A formed by the intersection of rows c and d and columns a and b.
  • A([a b c...],[e f g...]) returns the subarray of A formed by the intersection of rows a,b,c,... and columns e,f,g,...
  • A(:,c:d) returns the subarray of A consisting of all the rows of A and the c-th through d-th columns, inclusive.
  • A(:,[c d e ...]) returns the subarray of A formed by all rows and columns c,d,e,...
  • A(a:b,:) returns the subarray of A formed by all the columns of A and the a-th through b-th rows, inclusive.
  • A([a b c...],:) returns the subarray of A formed by all the columns of A and rows a,b,c,...
  • A(a,:) returns the a-th row of the matrix A.
  • A(:,b) returns the b-th column of the matrix A.
  • A (:) returns a column vector whose elements are columns of A placed in order below one another.
  • A(:,:) is equivalent to all rows and columns of the matrix A.
  • [A, B, C,...] returns the matrix formed by A, B, C,...
  • SA = [] deletes the subarray S of the matrix A, and returns the remaining matrix.
  • diag(v) creates a diagonal matrix with the vector v in the diagonal.
  • diag(A) returns the diagonal of the matrix A as a column vector.
  • flipud(A) returns the matrix whose rows are placed in reverse order (from top to bottom) to the rows of A.
  • fliplr(A) returns the matrix whose columns are placed in reverse order (from left to right) to those of A.
  • rot90(A) rotates the matrix A 90 degrees counterclockwise.
  • reshape(A,m,n) returns the m × n matrix extracted from the matrix A, where consecutive elements of the original matrix fill the new matrix column by column.
  • size(A) returns the order (size) of the matrix A.
  • find(condA) returns the items in A that satisfy the stated condition.
  • length(v) returns the length of the vector v.
  • tril(A) returns the lower triangular part of the matrix A.
  • triu(A) returns the upper triangular part of the matrix A.
  • A' returns the transpose of the matrix A.
  • inv(A) returns the inverse of the matrix A.

The most important operations with array variables are summarized below:

  • A + B, A - B, A * B sum, difference and product of matrices.
  • AB  If A is square, AB = inv (A) * B. If A is not square, AB is the solution, in the sense of least-squares, of the system AX = B.
  • B/A coincides with (A'B')'.
  • A^n coincides with A * A * A *... * A n times (nth power).
  • P^A performs the calculation only if p is a scalar.

1-4. Character Variables

MATLAB is capable of powerful numerical calculation, but it also provides versatility in handling character variables (text variables). A character variable (string) is simply a string of characters, included in single quotes, which MATLAB treats as a vector. For example:

>> c = 'string'
c =

string

We have thus defined the variable c as a character variable. Among the MATLAB commands that handle character variables are the following:

  • abs('string') returns the vector whose elements are the ASCII values of the characters in the string.
  • setstr(numeric_vector) returns the string of ASCII characters that are equivalent to the elements of the vector.
  • str2mat(t1,t2,t3,...) returns the matrix whose rows are the strings t1, t2, t3,..., respectively.
  • str2num('string') converts the string of characters into an exact numerical value using eval.
  • num2str(number) converts the number into its string of equivalent characters with fixed precision.
  • int2str(integer) converts the integer into a string.
  • sprintf('format', A) converts the exact numeric array A into a string using the specified format.
  • sscanf('string', 'format') converts the string to a numeric value in the specified format.
  • dec2hex(integer) converts the decimal integer into its equivalent string in hexadecimal.
  • hex2dec('string_hex') converts the hexadecimal string into the equivalent integer.
  • hex2num('string_hex') converts the hexadecimal string into the equivalent IEEE floating-point number.
  • lower('string') converts the string to lowercase.
  • upper('string') converts the string to uppercase.
  • strcmp(s1,s2) compares the strings s1 and s2 and returns 1 if they are equal, and 0 otherwise.
  • strcmp(s1,s2,n) compares the strings s1 and s2 and returns 1 if they are equal in their first n characters and 0 otherwise.
  • strrep(c, 'exp1', 'exp2') replaces exp1 with exp2 in the string c.
  • findstr(c, 'exp') returns the position of the expression exp in the string c.
  • isstr(expression) or ischar(expression) returns 1 if the expression is a string and 0 if it is not.
  • strjust(string) right-justifies the string.
  • blanks(n) generates a string of n blank characters.
  • deblank(string) replaces the characters in the string with blanks.
  • eval(expression) executes the expression even if it is a string.
  • disp('string') displays the string (or array) as written. MATLAB then continues processing.
  • input('string') displays the string on screen, then MATLAB pauses until the user presses a key to continue.

Here are some examples:

>> eval('4 * atan(1)')
ans =

3.1416

In the following examples you can see how MATLAB numerically evaluates the contents of a string (provided it is in a form recognized by the program):

>> hex2dec('3ffe56e')
ans =

67102062

Here, MATLAB has returned a decimal from a string in hexadecimal. The opposite conversion looks like this:

>> dec2hex(1345679001)
ans =

50356E99

Here, the program has converted a decimal number to a hexadecimal string.

>> sprintf('%f',[1+sqrt(5)/2,pi])
ans =

2.118034 3.141593

With sprintf, the exact numerical components of a vector have been converted to a string (with default precision).

>> sscanf('121.00012', '%f')
ans =

121.0001

With sscanf, a numeric string was returned in exact numerical format (with default precision).

>> num2str (pi)
ans =

3.142

The exact number is now the value of π as a string.

>> str2num('15/14')
ans =

1.0714

A string has been converted to an exact numeric value, with default accuracy.

>> setstr(32:126)
ans =

!"#$% &' () * +, -. / 0123456789:; < = >? @ABCDEFGHIJKLMNOPQRSTUVWXYZ [] ^
 _'abcdefghijklmnopqrstuvwxyz {|}~

This operation obtained the ASCII characters associated with the whole numbers between 32 and 126.

>> abs('{]}><#¡¿?°ª')
ans =
123 93 125 62 60 35 161 191 63 186 170

With the abs command we have obtained the integers corresponding to each ASCII character specified in its argument.

>> lower('ABCDefgHIJ')
ans =

abcdefghij

This command translated the text to lowercase.

>> upper('abcd eFGHi jKlMn')
ans =

ABCD EFGHI JKLMN

Here we have converted the text to uppercase.

>> str2mat ('The world','The country','Daily 16','ABC')
ans =

The world
The country
Daily 16
ABC

The str2mat command has created an array of text whose rows are the strings specified as its arguments.

>> disp('This text will appear on the screen')
This text will appear on the screen

This command has displayed as screen text the argument of the command disp.

>> c = This is 'a good example';
>> strrep(c, 'good', 'bad')
ans =

This is a bad example

This command has replaced good with bad in the string c. The following command finds the position that the expression is occupies within the string c.

>> findstr(c, 'is')
ans =

3 6

1-5. Logic Functions

MATLAB has a group of functions whose output is either true (value 1) or false (value 0). Among them are the following:

  • exist(A) tests whether the variable or function A exists (returns 0 if A does not exist, and a number between 1 and 5, depending on the type, if it does exist).
  • any(V) returns 0 if all elements of the vector V are zero, and returns 1 if some element of V is non-null.
  • any(A) returns 0 for each column of the matrix A with all null elements, and returns 1 for each column of the matrix A that has some non-null elements.
  • all(V) returns 1 if all the elements of the vector V are non-null, and returns 0 if some element of V is zero.
  • all(A) returns 1 for each column of the matrix A in which no elements are null, and returns 0 for each column of A that has any null elements.
  • find(V) returns the places (or indices) occupied by the non-zero elements of the vector V.
  • isNaN(V) returns 1 for the elements of V that are indeterminate, and returns 0 for those that are not.
  • isinf(V) returns 1 for the elements of V that are infinite, and returns 0 for those that are not.
  • isfinite(V) returns 1 for the elements of V that are finite, and returns 0 for those that are not.
  • isempty(A) returns 1 if A is an empty array, and returns 0 otherwise (an empty array is one that has one of its dimensions equal to 0).
  • issparse(A) returns 1 if A is sparse, and returns 0 otherwise.
  • isreal(V) returns 1 if all the elements of V are real, and 0 otherwise.
  • isprime(V) returns 1 for all elements of V that are prime numbers, and returns 0 for elements of V that are not prime.
  • islogical(V) returns 1 if V is a logical vector and 0 otherwise.
  • isnumeric(V) returns 1 if V is a numeric vector and 0 otherwise.
  • ishold returns 1 if hold is on and 0 otherwise. When hold is on the current plot and (most) axis properties are held so that subsequent graphing commands add to the existing graph.
  • isieee returns 1 if the computer uses IEEE arithmetic and 0 otherwise.
  • isstr(S) returns 1 if S is a string, and 0 otherwise.
  • ischart(S) returns 1 if S is a string, and 0 otherwise.
  • isglobal(A) returns 1 if A is a global variable, and 0 otherwise.
  • isletter(S) returns 1 if S is a letter of the alphabet, and 0 otherwise.
  • isequal(A,B) returns 1 if the matrices or vectors A and B are equal, and 0 otherwise.
  • ismember(V,W) returns 1 for every element of V that is in W, and 0 for every element of V that is not in W.

Here are some examples:

>> isinf([pi NaN Inf -Inf])
ans =

0     0     1     1
>> any([pi NaN Inf -Inf])
ans =

1
>> ismember([1,2,3,5],[8,12,1,3,56,5])
ans =

1     0     1     1
>> A = [2,0,1]; B = [4,0,2];
>> isequal(2*A,B)
ans =

1
>> V=[-10,5,3,12,0];
>> isprime(V)
ans =

0     1     1     0     0
>> isnumeric(V)
ans =

1
>> all(V)
ans =

0
>> any(V)
ans =

1
>> C = [0 2 3;0 1 2 ;0 4 6],D = [0 0 0 0;4 3 1 2;6 0 0 4]
>> any(C),all(C),any(D),all(D)
ans =

0 1 1

ans =

0 1 1

ans =

1 1 1 1

ans =

0 0 0 0

1-6. Elementary Functions That Support Complex Symbolic Matrices as Arguments

  • Trigonometric

    sin(z)

    sine function

    sinh(z)

    hyperbolic sine function

    asin(z)

    arcsine function

    asinh(z)

    hyperbolic arcsine function

    cos(z)

    cosine function

    cosh(z)

    hyperbolic cosine function

    acos(z)

    arccosine function

    acosh(z)

    hyperbolic arccosine function

    tan(z)

    tangent function

    tanh(z)

    hyperbolic tangent function

    atan(z)

    arctangent function

    atan2(z)

    arctangent function in the fourth quadrant

    atanh(z)

    hyperbolic arctangent function

    sec(z)

    secant function

    sech(z)

    hyperbolic secant function

    asec(z)

    arcsecant function

    asech(z)

    hyperbolic arcsecant function

    csc(z)

    cosecant function

    csch(z)

    hyperbolic cosecant function

    acsc(z)

    arccosecant function

    acsch(z)

    hyperbolic arccosecant function

    cot(z)

    cotangent function

    coth(z)

    hyperbolic cotangent function

    acot(z)

    arccotangent function

    acoth(z)

    hyperbolic arccotangent function

  • Exponential

    exp(z)

    base e exponential function

    log(z)

    Napierian logarithm function

    log10(z)

    decimal logarithm function

    sqrt(z)

    square root function

  • Complex

    abs(z)

    modulus or absolute value

    angle(z)

    argument

    conj(z)

    complex conjugate

    imag(z)

    imaginary part

    real(z)

    real part

  • Numerical

    fix(Z)

    removes the decimal part

    floor(Z)

    rounds decimals to the nearest lower integer

    ceil(Z)

    rounds decimals to the nearest greater integer

    round(Z)

    rounds Z to the nearest integer, rounding values mid way between two integers to the integer with the largest magnitude.

    rem(Z1, Z2)

    remainder of the division of Z1 by Z2

    sign(Z)

    sign function

  • Matrix

    expm(Z)

    matrix exponential function by default

    expm1(Z)

    matrix exponential function in M-file

    expm2(Z)

    matrix exponential function via Taylor series

    expm3(Z)

    matrix exponential function via eigenvalues

    logm(Z)

    matrix logarithm

    sqrtm(Z)

    matrix square root

    funm(Z,'function')

    applies the function to the array Z

1-7. Symbolic Functions of Several Variables

Functions of one or several variables are defined using the command maple as follows:

  • maple('f: = x - > f (x)') or  maple f: = x - > f (x) defines the function f(x).
  • maple ('f:=(x,y,z...)- > f(x,y,z...)') defines the function f(x,y,z,..).
  • maple ('f:=(x,y,z...)- > (f1 (x,y...), f2(x,y..),...)') defines the vector function (f1(x,y,..), f2(x,y,..),...).

To find the value of the function (x, y, z) - > f (x,y,z...) at the point (a, b, c,...), use the expression maple('f(a,b,c,...)').

We can find the value of the vector function f :=(x,y,..)-> ( f 1(x,y,..), f 2(x,y,..),...) at the point (a,b,...) by using the expression maple('f(a,b,..)').

The function f (x,y) = 2x + y is defined in the following way:

>> maple ('f:=(x,y) - > 2 * x + y '),

f(2,3) and f(a,b) are calculated as follows:

>> maple('f(2,3)')
ans =

7
>> maple('f(a,b)')
ans =

2 * a + b

EXERCISE 1-5

Given the function h, defined as  h(x,y) = (cos(x2-y2), sin(x2-y2)); calculate h(1,2), h(-Pi,Pi) and h(cos(a2), cos(1 -a2)).

Because we have a vector function of two variables, we use the maple command:

>> maple ('h:=(x,y) - > (cos(x^2-y^2), sin(x^2-y^2))'),
>> maple ('A = h(1,2), B = h(-pi,pi), C = h (cos(a^2), cos(1-a^2))')

ans =

A = (cos(3),-sin(3)), B = (1,0),
C = (cos(cos(a^2)^2-cos(-1+a^2)^2), sin(cos(a^2)^2-cos(-1+a^2)^2))

1-8. Functions of Single Variables

Functions of a single variable are a special case of vector functions, but they can also be defined in MATLAB via: f = 'function'. To find the value of the function f at a point, you use the command subs, whose syntax is as follows:

  • subs(f, a) applies the function f at the point a
  • subs(f, a, b) substitutes each occurrence of a by b in the expression f.

Let’s see how to define the function f (x) = x ^ 2 :

>> f ='x ^ 2'
f =

x ^ 2

Now we calculate the values f (4), f (a+1) and f (3x+x^2):

>> syms a x
>>  A=subs(f,4),B=subs(f,a+1),C=subs(f,3*x+x^2)
A =

16

B =

(a+1) ^ 2

C =

(3 * x + x ^ 2) ^ 2

It should also be borne in mind that if we use the maple command, the special constants π ,e, i, and ∞ are defined as maple('Pi'), maple('exp (1)'), maple('i') and maple('infinity'), respectively.

EXERCISE 1-6

Define the functions f (x) = x2, g (x) = x1/2 and h (x) = x + sin (x). Calculate f (2), g (4) and h (a-b2).

>> f ='x^2'; g = 'x^(1/2)'; h = 'x+sin(x)';

>> syms a b
>> a = subs(f,2), b = subs(g,4), c = subs(h,'a-b^2')

A =

4

b =

4 ^(1/2)

c =

a - b^2 + sin(a-b^2)

We could also have done the following:

>> maple('f:=x->x^2: g:=x->sqrt(x):h:=x->x+sin(x)'),
>> maple('f(2),g(4),h(a-b^2)')

ans =

4, 2, a - b^2 + sin(a-b^2)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset