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:
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.
The most important operations with array variables are summarized below:
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:
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:
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
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 |
exp(z) |
base e exponential function |
log(z) |
Napierian logarithm function |
log10(z) |
decimal logarithm function |
sqrt(z) |
square root function |
abs(z) |
modulus or absolute value |
angle(z) |
argument |
conj(z) |
complex conjugate |
imag(z) |
imaginary part |
real(z) |
real part |
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 |
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:
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:
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)