Professional Documents
Culture Documents
MATRIX ALGEBRA With MATHEMATICA PDF
MATRIX ALGEBRA With MATHEMATICA PDF
MATRIX ALGEBRA With MATHEMATICA PDF
ALGEBRA WITH
MATHEMATICA
CSAR PREZ LPEZ
INDEX
PRACTICAL INTRODUCTION TO MATHEMATICA LANGUAGE
1.1 NUMERIC CALCULUS WITH MATHEMATICA
1.2 SYMBOLIC CALCULUS WITH MATHEMATICA
1.3 GRAPHICS WITH MATHEMATICA
1.4 GENERAL NOTATION AND USE OF PREVIOUS RESULTS
1.5 HELP WITH COMMANDS
1.6 MATH SYMBOLS, OPERATORS AND FLOW CONTROL SENTENCES
1.7 PACKAGES
1.8 FILES AND EXTERNAL OPERATIONS
1.9 OTHER CHARACTERISTICS OF EDITION
1.10 TRANSLATING EXPRESSIONS TO LANGUAGES C, FORTRAN AND TEX
1.11 MATHEMATICA AND THE PROGRAMMING
1.12 MATHEMATICA AND THE COMMUNICATIONS
MATRIX ALGEBRA
2.1 VECTORS
2.2 OPERATIONS WITH VECTORS
2.3 MATRICES
2.4 OPERATIONS WITH MATRICES
2.5 SPECIAL OPERATIONS WITH MATRICES
2.6 DECOMPOSITION OF MATRICES
2.7 RANGE OF A MATRIX
2.8 SEMEJANT MATRICES AND DIAGONALIZATION
APPLICATIONS WITH MATRICES. VECTOR SPACES AND LINEAR APPLICATIONS.
3.1 LINEAR INDEPENDENCE. BASES. CHANGE OF BASIS
3.2 LINEAR APPLICATIONS
3.3 QUADRATIC FORMS
APPLICATIONS OF MATRICES. EQUATIONS AND SYSTEMS
4.1 RESOLUTION OF EQUATIONS
4.2 SPECIAL COMMANDS TO SOLVE EQUATIONS
4.3 NUMERICAL METHODS FOR RESOLUTION OF EQUATIONS
4.4 SYSTEMS OF EQUATIONS
4.5 SYSTEMS OF LINEAR EQUATIONS
4.6 ROUCHE -FROBENIUS THEOREM
4.7 HOMOGENEOUS SYSTEMS
MATRIX STRUCTURES. LISTS, TABLES, ARRAYS, RULES AND PATTERNS
5.1 LISTS
5.2 LIST CONCEPT AND FIRST PROPERTIES
5.3 BUILDING TABLES OF VALUES USING LISTS. RANGE AND ARRAY FUNCTIONS
5.4 WORKING WITH COMPONENTS OF LISTS
5.5 REFERENCING COMPONENTS OF LISTS
5.6 COMBINATION OF LISTS
5.7 REORDERING LISTS
5.8 FUNCTIONS TO COUNT, CHANGE SHAPE, SELECT AND SEARCH ITEMS FROM LISTS
5.9 APPLYING FUNCTIONS TO LISTS
5.10 MATHEMATICALS OPERATIONS WITH LISTS
5.11 RULES
5.12 EQUALITY
5.13 IMMEDIATE RULES
5.14 DEFERRED RULES
5.15 PATTERNS
Chapter 1.
PRACTICAL INTRODUCTION TO
MATHEMATICA LANGUAGE
1.1 NUMERIC CALCULUS WITH MATHEMATICA
We can use Mathematica as a powerful numerical computer. Most calculators handle
numbers only with a degree of precision preset, however Mathematica makes exact
calculations with precision which is necessary. In addition, unlike calculators, we can
perform operations not only with individual numbers, but also with objects such as arrays.
Most of the themes of the classical numerical calculus, are treated in this software. It
supports matrix calculus, statistics, interpolation, fit by least squares, numerical
integration, minimization of functions, linear programming, numerical algebraic and
differential equations resolution and a long list of processes of numerical analysis that
well see as the successive issues of this book.
Here are some examples of numerical calculus with Mathematica. (As we all know, to
get the results necessary type mayusculas+enter once written corresponding expressions)
(1) We can simply calculate 4 + 3 and get as a result 7, to do this, just type 4 + 3 (and
then shift + Enter).
In [1]: = 4 + 3
Out [1] = 7
(2) Also we can get the exact value of 3 high at 100, without having previously set
precision, just for this purpose press 3 ^ 100.
In [2]: = 3 ^ 100
Out [2] = 515377520732011331036461129765621272702107522001
(3) Also we can use the N function to pass the result of the operation immediately prior
to scientific notation. To do this, type N [%] (symbol % we use to refer to the immediately
preceding calculation).
In [3]: = N [%]
47
Out [3] = 5.153775207320114 10
(4) Also we can perform operations with a fixed degree of precision. If we find the
square root of 5 with 25 digits, simply enter the expression N [Sqrt [5], 25].
In [4]: = N [Sqrt [5], 25]
Out [4] = 2.2360679774997896964091737
(5) Also we can work with complex numbers. We will get the result of the operation (2
+ 3i) raised to 10, by typing the expression (2 + 3I) ^ 10.
In [5]: = (2 + 3 * I) ^ 10
Out [5] = 341525 145668 I
(6) Also we can calculate the value of the Bessel function in section 13.5. This type
BesselJ [0,13.5].
In [6]: = BesselJ [0, 13.5]
Out [6] = 0.2149891658804008
(7) Also can calculate the value of Rieman function Z at the point (1/2 + 13i) with 15
digits. Just press N [Zeta [1/2 + 13I], 15].
I In[7] := N[Zeta[1/2 + 13*I], 15]
Out [7] = 0.4430047825053677 0.6554830983211705
(8) Also we can perform numeric integrals. To calculate the integral between 0 and p of
(SIN(x)) sine function type expression NIntegrate [Sin [no [x]], {x, 0, Pi}].
In [8]: = NIntegrate [Sin [no [x]], {x, 0, Pi}]
Out [8] = 1.78648748195006.
These themes will be treated more thoroughly in successive chapters throughout the
book.
1.2 SYMBOLIC CALCULUS WITH MATHEMATICA
Mathematica perfectly handled the symbolic mathematical computation, manipulating
formulae and algebraic expressions easily and quickly and can perform the majority of
algebraic operations. You can expand, factor and simplify polynomials and rational and
trigonometric expressions, you can find algebraic solutions of polynomial equations and
systems of equations, can evaluate derivatives and integrals symbolically and find
functions solution of differential equations, you can manipulate powers, limits and many
other facets of algebraic mathematics series.
Here are some examples of symbolic computation with Mathematica.
1) We can raise the bucket the following algebraic expression: (x + 1) (x+2) (x+2) ^ 2.
This is done by typing the following expression: Expand [((x + 1) (x+2) (x+2) ^ 2) ^ 3].
The result will be another algebraic expression:
In [1]: = Expand [((x + 1) *(x + 2) (x + 2) ^ 2) ^ 3]
2 3
Out [1] = 8- 12 x- 6 x- x
2) We can factor the result of the calculation on the previous example by typing Factor
[%]
In [2]: = Factor [%]
3
Out [2] = (2 + x)
3) We can resolve the indefinite integral of the function (x ^ 2) Sin(x) ^ 2 by typing
Integrate [x ^ 2 Sin [x] ^ 2 x]
In[3] := Integrate[x^2*Sin[x]^2, x]
Out[3]=
3 2
x x Cos [2 x] (1- 2 x) Sin [2 x]
+
6 4 8
4) We can find the derivative of the result of the integral above by typing D [% x]
In[4] := D[%, x]
Out[4] =
2 2
x Cos[2 x] (1 2 x ) Cos[2 x]
+-
2 4 4
5) We can simplify the result of the derivative before typing Simplify [%]
In[5] := Simplify[%]
2 2
Out[5] = x Sin[x]
6) We can develop in power of order 14 series the result from the previous example by
typing Series [% {x, 0.14}]
In[6] := Series[%, {x, 0, 14}]
Out[6] =
6 8 10 12 14
4 x 2 x x 2 x 2 x 15
x + +- + O[x]
3 45 315 14175 467775
7) We can solve the equation 3ax - 7 x ^ 2 + x ^ 3 = 0 (a, is a parameter) by typing Solve
[3ax 7 x ^ 2 + x ^ 3 = 0]
Out[7] =
1/3
7 49 2
{{x >- + +
3 2 1/3
3 (686 81 ax + 9 Sqrt[1372 ax + 81 ax ] )
2 1/3
(686 81 ax + 9 Sqrt[1372 ax + 81 ax ] )
+ -},
1/3
3 2
1/3
7 I 49 2
{x > + Sqrt[3] ( +
3 2 2 1/3
3(68681ax+9Sqrt[1372ax+81ax ] )
2 1/3
(686 81 ax + 9 Sqrt[1372 ax + 81 ax ] )
+ )
1/3
3 2
1/3
49 2
- ( +
2 1/3
3 (686 81 ax + 9 Sqrt[1372 ax + 81 ax ] )
2 1/3
(686 81 ax + 9 Sqrt[1372 ax + 81 ax ] )
+ -) / 2},
1/3
3 2
1/3
7 I 49 2
{x > Sqrt[3] (- +
3 2 2 1/3
3 (68681ax+9 Sqrt[1372ax+81ax ] )
2 1/3
(686 81 ax + 9 Sqrt[1372 ax + 81 ax ] )
+ -)
1/3
3 2
1/3
49 2
(- +
2 1/3
3 (686 81 ax + 9 Sqrt[1372 ax + 81 ax ] )
2 1/3
(686 81 ax + Sqrt 9 [1372 ax + 81 ax])
+ ) / 2}}
1/3
3 2
8) We can find five complex solutions of the equation x ^ 5 + 2 x + 1 = 0 by typing
NSolve [x ^ 5 + 2 x + 1 = 0, x]
In[8] := NSolve[x^5 + 2*x + 1 == 0, x]
Out[8] = {{x > 0.7018735688558619 0.879697197929824 I},
{x > 0.7018735688558619 + 0.879697197929824 I},
{x > 0.486389035934543},
{x > 0.945068086823133 0.854517514439046 I},
{{x > 0.945068086823133 + 0.854517514439046 I}}
9) We can generate a matrix 3 x 3 whose (i, j) element is 1 / (i+j+1) by typing m =
Table [1 / (i + j + 1), {i, 3}, {j, 3}]
In[9] := m = Table[1/(i + j + 1), {i, 3}, {j, 3}]
Out [9] = {{1/3, 1/4, 1/5}, {1/4, 1/5, 1/6}, {1/5, 1/6, 1/7}}
10) We can invert the matrix above, typing Inverse [m]
In [10]: = Inverse [m]
Out [10] = {{300, 900, 630}, {900, 2880, 2100}, {630, 2100, 1575}}
11) We can find the determinant of the matrix m xIdentidad (3.3)
tecleando Det[ m x IdentityMatrix[3] ]
In[11] := Det[m x*IdentityMatrix[3]]
2 3
Out [11] = (1 4755 x + 255600 x - 378000 x ) / 378000
12) We can find all the permutations of the three elements {e, f, g}
tecleando Permutations[{e, f, g}]
In[12] := Permutations[{e, f, g}]
Out[12] = {{e, f, g}, {e, g, f}, {f, e, g}, {f, g, e}, {g, e, f}, {g, f, e}}
13) We can define the function f (x) = x ^ 2, variable x, the explicit form:
In [13]: = f [x_] = x ^ 2;
14) We can create pure functions that do not have explicit typing for example,
definitions Map [Function [x, 1 + x ^ 2], {a, b, c, d}]
In[14] := Map[Function[x,1+x^2], {a,b,c,d}]
Out [14] =
2 2 2 2
{1 + a, 1 + b, 1 + c, 1 + d }
All of these concepts will be expanded in the corresponding chapters.
1.3 GRAPHICS WITH MATHEMATICA
Mathematica produces two and three-dimensional graphics, as well as outlines and
graphics of density, you can represent the graphics and list data, allows to control colors,
shading and other graphics features, also supports animated graphics. Produced by
Mathematica graphics are portable to other programs.
Here are some examples of graphics with Mathematica
We can represent the function Seno (1/x) for x ranging between 0 and pi typing Plot
[Sin[1/x], {x, 0, Pi}]. See Figure 1.1
Figure 1.1
We can give options of framework and grid to the graph above, by typing Show [%,
Frame > True, FrameLabel > {time, Signal}, GridLines > Automatic]. See Figure 1.2.
Figure 1.2
We can generate a graphic of contour for the sine function Sin(x+Sin(y)), by typing
ContourPlot [Sin[x + Sin[y]], {x, 2, 2}, {y, 2, 2}]. See Figure 1.3.
Figure 1.3
We can generate a three-dimensional graph, typing Plot3D [Cos [x + Cos [y]], {x, 3, 3},
{y, 3, 3}]. See Figure 1.4.
These 3D graphics allow perfection to get an idea of the figures in space, and are very
helpful in visually identifying intersections between different bodies, generation of
developments of all kinds and volumes of revolution.
Figure 1.4
We can represent a surface given by the parametric coordinates x = uCos(t). y = u sine
(t), z = t/2 by typing the expression: ParametricPlot3D [{uCos[t], uSin[t], t/2}, {t, 0, 15},
{u, 1, 1}, tick > None]. See Figure 1.5.
Figure 1.5
We can combine in the same graph the two previous charts by typing Show [% %].
In the corresponding chapter of graphics we will extend these concepts.
1.4 GENERAL NOTATION AND USE OF PREVIOUS
RESULTS
Whenever a program is used, it is necessary to know the General characteristics about
notation, with the aim of introducing us to practice with the same. The best way to learn
how Mathematica is to use the program. Each example consists of the input of the user
In[n] -led and led Mathematica response with Out[n].
It is necessary to pay attention in the difference between uppercase and lowercase
letters, type parentheses or keys, the amount of spaces and punctuation (commas,
semicolons).
As the C programming language, Mathematica is sensitive to the difference between
uppercase and lowercase letters, for example, [x] is different without [x]. The names of all
built-in functions begin with a capital letter. Each bracket has its own sense, as we will see
later in this chapter.
You must put spaces between variables that must be multiplied, and must not have
spaces in the names of commands, or symbols of more than one letter in the names of
functions. In other cases, spaces are not considered. They can be some to make their input
more readable.
It has already been said that the names of all functions, variables, options and constants
built into Mathematica starting with uppercase letters, for example, Integrate, Plot. If a
name consists of two or more words, the first letter of each word is capitalized, for
example, ContourPlot, InterpolatingPolymial and MapAt.
The majority of objects built into Mathematica are complete words. Unlike Unix, MS-
DOS and other systems, Mathematica rarely uses abbreviations. Abbreviations are only
used when they are widely known (Abs, Cos, D, Det, GCD, etc.).
Using Mathematica is like hold a conversation. Make a question and Mathematica will
respond with a result. Mathematica assigns a sequential number for each input/output pair.
The nth input from the user carries the label In [n] and the corresponding output of the
computer carries Out [n]. It is possible to refer to inputs and outputs earlier thanks to these
labels.
The % symbol is used to refer to the previous result.
The symbol % is used to refer to the previous 2 times result.
The symbol % % (k times) is used to refer to the previous times k result.
The symbol % n is used to refer to the output number n (Out [n]).
Here are some examples in this regard.
10
Firstly, intends to Mathematica to calculate 5.
In [1]: = 5 ^ 10
Out [1] = 9765625
The number assigned to an output then can be used to reference any previous result. We
can check the previous result by taking the root of order 10 of the result Out [1], which
can be abbreviated with %1.
In [2]: = %1^(1/10)
Out [2] = 5
Most often is that the user wants to refer to its most recent result. The % character
refers to the most recent result. In the following example, % is replaced by the last
calculated result, i.e. 5.
In [3]: = % + to
Out [3] = 5 + a
It can refer to a previous result by using one or more percent signs; i.e., % refers to the
last result, %% to the penultimate, %% to the penultimate, and so on. It is also possible to
refer to a previous result in concrete using %n, where n is the number of the output line.
Other examples are presented below
In[4]:= 77 ^ 2
Out[4]= 5929
In[5]:= % + 1
Out[5]= 5930
In[6]:= 3 % + % ^ 2 + %%
Out [6] = 35188619
In [7]: = 2% + 3%
Out [7] = 35194549
Note: When you start Mathematica, already not you can refer to the results obtained in
the previous session.
Units may be associated with values. Be sure to leave a space between the value and the
unit symbol. Mathematica evaluates combining the terms whenever possible.
In [8]: = 2 m + 3 m
Out [8] = 5 m
1.5 HELP WITH COMMANDS
It is possible to get help using the drop down menus of Mathematica.
But in addition, support can also be obtained through commands (instructions or
functions), implemented as objects of Mathematica.
You can use the help of immediate access to access various information, including the
names of the orders. The ? operator allows you to access information about a particular
object (command, function, etc.). The question mark should be first in line. The symbol *
combined with the operator? It acts as wildcard, i.e. it can fit with any alphanumeric
character or a sequence of them. If more than one order matches the request, Mathematica
lists the names of all of them. ? Operator expands the information about an object.
With the expression ?Factor * as input, Mathematica list the commands that begin with
the word Factor.
In[1]:= ?Factor*
Factor FactorInteger FactorSquareFreeList FactorComplete
FactorList FactorTerms Factorial FactorSquareFree Factorial2
FactorTermsList
If only an order conforms to the request (does not contain the symbol *), Mathematica
displays the instruction of use associated with the order. This instruction is, typically, a
template that shows how to invoke the order, i.e., what you expect the command as an
argument. Here is what I get if I ask for information about the order FactorInteger.
In[2]:= ?FactorInteger
FactorInteger[n] gives a list of the prime factors of the integer n, together with their
exponents.
(FactorInteger [n] gives a list of the prime factors of the integer n, along with its exponents)
This phrase indicates that this function expects an integer argument. For example, with
FactorInteger, I can find the prime factors of 75.
In [3]: = FactorInteger [75]
Out [3] = {{3, 1}, {5, 2}}
This result indicates that 75 is equal to 3 ^ 1 * 5 ^ 2.
Then we can, thanks to this help, information about a particular function that write the
sign of close of polling and then its name.
The wildcard character (*) is particularly useful to browse between the built-in
commands. For example, to know the names of some of the graphics commands, the names
of the orders which contain the words Graphic or Plot can be ordered.
In[4]:= ?*Graphics*
ContourGraphics Graphics Graphics3D
DensityGraphics GraphicsArray SurfaceGraphics
FullGraphics GraphicsSpacing
In[5]:= ?*Plot*
ContourPlot ParametricPlot3D PlotPoints
DensityPlot Plot PlotRange
PlotColor ListContourPlot PlotRegion
PlotDivision ListDensityPlot PlotDivision
ListPlot PLotJoined Plot3D
ListPlot3D PlotLabel Plot3Matrix
PlotStyle ParametricPlot
Then, for information of those functions whose name contains a particular script, you
must write the same between two symbols * (wildcard), and order information with the
symbol?. We will use the double question mark ? to get additional information about a
function, variable, option or other object.
In[6]:= ??Plot
Plot[f, {x, xmin, xmax}] generates a plot of f as a function of x from xmin to salt
The values are obtained by default Plot options. These options specify the minimum
number of points showing Mathematica to determine the form of a chart, the position of the
axes, the size of the picture, among other things.
Here are some more examples.
In [7]: =? Graphics *
Graphics GraphicsSpacing Graphics3DGraphicsArray
Returns the three commands that start with Graphics.
In[8]:= ?GraphicsArray
GraphicsArray[g1,g2,] represents a row of graphic objects. GraphicsArray[g11,g12,,
] represents a two - dimensional array o graphic objects.
Returns both the structure of the function and a brief explanation of its purpose.
In[9]:= ??GraphicsArray
GraphicsArray[{g1,g2,}]represents a row graphic objects. GraphicsArray[{{g11,g12,},
}]represents a two-dimensional array of graphic objects.
Attributes[GraphicsArray] = {Protected}
{AspectRatio -> Automatic, Axes -> False,
AxesLable -> None, AxesOrigin -> Automatic,
AxesStyle -> Automatic, Background -> Automatic,
ColorOutput -> Automatic, DefaultColor -> Automatic,
Epilog -> {}, Frame -> False, FrameLAbel -> none,
FrameStyle -> Automatic, FrameTicks -> None,
GraphicsSpacing -> 0.1, GriLines -> None,
PlotLabel -> None, PlotRange -> Automatic,
PlotRegion -> Automatic, Prolog -> {},
RotateLabel -> True, Ticks -> None,
DefaultFont :> $DefaultFont,
{DisplayFunction: > $DisplayFunction}
Returns, as well as the structure of the function and its explicaciion function and their
default values options.
As we have already seen, in Mathematica the names of functions and objects that are
defined in the program, begin with capital letter. But the user can define their own objects,
which normally should start with lowercase letters to not create conflict with the already
defined in the program.
To know at a certain point objects that begin with lowercase letters use the function ? @.
Finally, look at two new commands help. The Options command allows to get all the
options of a particular object and the Information command allows you to obtain further
information about these options, as shown in the following examples.
In[10] := Options[Plot]
Out[10] = {AspectRatio > GoldenRatio^(1), Axes > Automatic,
AxesLabel > None, AxesOrigin > Automatic, AxesStyle > Automatic,
Background > Automatic, ColorOutput > Automatic, Compiled > True,
DefaultColor > Automatic, Epilog > {}, Frame > False,
FrameLabel > None, FrameStyle > Automatic, FrameTicks > Automatic,
GridLines > None, MaxBend > 10., PlotDivision > 20., PlotLabel > None,
PlotPoints > 25, PlotRange > Automatic, PlotRegion > Automatic,
PlotStyle > Automatic, Prolog > {}, RotateLabel > True,
Ticks > Automatic, DefaultFont :> $DefaultFont,
DisplayFunction :> $DisplayFunction}
In[11] := Information[Plot]
Out[11] = {ContourPlot[f, {x, xmin, xmax}, {y, ymin, ymax}] generates a\ contour plot of f
as a function of x and y., DensityPlot[f, {x, xmin,\
xmax}, {y, ymin, ymax}] makes a density plot of f as a function of x and\
y., ListContourPlot[array] generates a contour plot from an array of\
height values., ListDensityPlot[array] generates a density plot from an\
array of height values., ListPlot[{y1, y2, }] plots a list of\
values. The x coordinates for each point are taken to be 1, 2, .\
ListPlot[{{x1, y1}, {x2, y2}, }] plots a list of values with specified\
x and y coordinates., ParametricPlot[{fx, fy}, {t, tmin, tmax}]\
produces a parametric plot with x and y coordinates fx and fy generated\
as a function of t. ParametricPlot[{{fx, fy}, {gx, gy}, }, {t, tmin,\
tmax}] plots several parametric curves., Plot[f, {x, xmin, xmax}]\
generates a plot of f as a function of x from xmin to xmax. Plot[{f1, f2,\
}, {x, xmin, xmax}] plots several functions fi.}
Lets look at an overview of the various forms of help by using commands, which
presents each command and a description of their functions.
Command Description
-
? var shows information about var
?? var shows more information about var
? xyz * l list objects whose name starts with xyz
? * xyz * list objects whose name contains xyz
? @ list objects whose name starts with no capital letter
Options list options of an object
Information provides additional information on the options of an object.
1.6 MATH SYMBOLS, OPERATORS AND FLOW
CONTROL SENTENCES
Mathematica uses conventional symbols used in the mathematical calculation. Normally
Mathematica uses English words, but allows you to refer to the standard mathematical
functions using symbols rather than words, i.e., symbols such as +, -, *, /, >, or > instead of
the words Plus, Minus, Times, Divide, Less or Greater.
Mathematical symbol function
-
+ Plus
+ Minus, Subtract
* Times
/ Split
^ Power
! Factorial
< Less
< = LessEqual
> Greater
> = GreaterEqual
Mathematica also provides symbols to denote logical, relational, conditional and
structure operations (flow control sentences IF, WHILE, DO, WHICH, FOR).
Mathematical symbol function
-
x == y equality
x! = y inequality
! p Not
p && q && . And
p || q || . Or
Xor [p, q,] Or exclusive
LogicalExpand[expr] expands logical expressions
If [p, then, else] Runs then if p is true and runs else if p is false
While [cond, expr] expr is evaluated while the condition cond is true
Which[cond1,expr1,,condn,exprn]
Consecutively evaluates cond1, condn conditions until
that is one that is true and returns the value of the
expression associated
Do [expr, {n}] evaluated n times the expression expr
Do [expr, [{i, imin, imax, di}]
Repeatedly evaluates the expression for values of i ranging
from imin to imax with successive increments of di.]
For [expr1, condition, increment, expr2]
evaluates Expr1 and follows sequentially evaluating expr2
and incrment until the condition is true.
Likewise how information about a function is available, information about a
mathematical symbol or other special shapes can be ordered to Mathematica.
In[1]:= ?<
x < y yields True if x is determined to be less than y. x1 < x2 < x3 yields True if the xi form
a strictly increasing sequence.
(x < and gives True, true, if it is determined that x is less than y. 1 x < x 2 < x3 gives True if
the xi form a strictly increasing sequence).
Mathematical symbols and other special shapes are aliases of functions included in
Mathematica.
The Alias function returns the function which corresponds to a special form.
In[2]:= Alias[<]
Out[2] = Less
In[3]:= Alias[=]
Out [3] = Set
Other symbols used in Mathematica are brackets (braces), parentheses (parentheses) and
keys (braces) are used for different purposes. Each of them has different meaning.
Parentheses are used to group. Without parentheses, the products and divisions take
precedence over the sums and differences.
In [4]: = 1 + 2 * 3
Out [4] = 7
In [5]: = 1 / 2-5
Out [5] =-(9/2)
Note that, with the use of parentheses, the grouping of the arguments changes.
In [6]: = (1 + 2) * 3
Out [6] = 9
In [7]: = 1 / (2-5)
Out [7] =-(1/3)
Brackets are used to specify arguments to functions. For example, the splitters function
requires a single argument, an integer, as you can see in his message of immediate help.
In[8]:= ?Divisors
Divisors[n] gives a list of the integers that divide n.
(Splitters [n] gives a list of integers that divide to n.)
When we invoke splitters with a number, Mathematica returns a list of integers that
divide the number.
In [9]: = splitters [100]
Out [9] = {1, 2, 4, 5, 10, 20, 25, 50, 100}
The result indicates that the integers 1, 2, 4, 5, 10, 20, 25, 50 and 100 divide 100.
Some functions, such as Random, do not require arguments. Although there is no
argument in the function, you must use the square brackets. If no argument is specified,
Random returns a real number between 0 and 1.
In[10]:= ?Random
Random[ ] gives a uniformly distributed pseudrandom Real in the range 0 to 1.
Random[type, range] gives a pseudorandom number of the specified type, lying in the
specified range. Possible types are: Integer, Real and Complex. The default range is 0 to 1.
You can give the range {min, max} explicitly; a range specification of max is equivalent to
{0, max}.
(Random [] gives a real pseudo random uniformly distributed between 0 and 1.)
Random [type, range] gives a pseudo random number of the specified type within the
specified range. Possible types are: Integer (integer), Real, and Complex (complex). The
default range is 0 to 1. The range {min, max} can be given explicitly; a specification of max
range is equivalent to {0, max}.)
In [11]: = Random]
Out [11] = 0.738551
Note that Random can be invoked with a single argument (a type) or with two arguments
(a type and a range, which is a couple indicating a minimum value and a maximum value).
In[12]:= Random[Integer]
Out[12] = 0
In[13]:= Random[Integer, {50, 60}]
Out [13] = 52
Some features require a fixed amount of arguments, while others can be invoked with
none, one or more arguments.
The keys are used to specify lists, vectors and matrices. A list or vector consists of
multiple expressions separated by commas and enclosed in braces.
In[14]:= {x, x^2, x^3}
2 3
Out[14]= {x, x , x }
In Mathematica, an array is represented as a list of lists. With Mathematica, you can
build an array of any dimension. Below you can see a matrix 2 by 2, whose elements are a
[i, j], where i specify the rank of the matrix and j the column.
In[15]:= {{a[1,1], a[1,2]}, {a[2,1], a[2,2]}}
Out[15]= {{a[1, 1], a[1, 2]}, {a[2, 1], a[2, 2]}}
Function MatrixForm presents the matrix in a more conventional way.
In[16]:= MatrixForm[{{a[1,1], a[1,2]}, {a[2,1], a[2,2]}}]
Out [16] = a [1, 1] to [1, 2]
to [2, 1] to [2, 2]
Since Mathematica makes extensive use of lists, both in terms of input as output, expand
the theme in the next chapter.
The double square brackets are used to index, i.e., to denote an object or set of objects
within a list. Suppose we have a vector v as follows.
In [17]: = v = {a, b, c}
Out [17] = {a, b, c}
The notation v [[i]] returns the i-th element of the vector or list called v provided that (i)
is entirely appropriate. It must be borne in mind that, in Mathematica, the numbering starts
from 1, in contrast to the C language that starts from 0.
In [18]: = v [[2]]
Out [18] = b
As seen above, in Mathematica an array is represented as a list of lists. We will assign the
name m to a 2 by 3 matrix.
In [19]: = m = {{1, 2, 3}, {4, 5, 6}}
Out[19] = {{1, 2, 3}, {4, 5, 6}}
In[20]:= MatrixForm[m]
Out[20]= 1 2 3
4 5 6
Note that I get the row i-th of the matrix m using m [[i]], if i is an appropriate integer.
In [21]: = m [[2]]
Out [21] = {4, 5, 6}
The notation m [[i, j] returns the j-th element of the row i th.]
In [22]: = m [2, 1]]
Out [22] = 4
Using the double brackets, you can select specific items from a list.
1.7 PACKAGES
Mathematica is an application written in c language. However, it has a language with
which to create new programs at the same time. A file that contains definitions written in the
own language of Mathematica is called package (package). To use the definitions contained in
it is necessary previously to load it. There are several ways of charging a pack. One of them is:
< < context PackageName
where is context the name of the directories or folders that contain the package.
For example:
In [1]: = < < Algebra SymbolicSum
When you execute this input, all additional programs are loaded in memory permanently
that will allow you to perform specific mathematical functions associated with symbolic
Algebra package sums.
Another way to load a package (package) is using the Needs statement. The advantage of
this latter option is that if the package is already loaded you will not load, thus saving
memory. In this case you must enter the order
Needs [context PackageName ]
For example:
In [2]: = Needs [ AlgebraSymbolicSum ]
It is important to give a recommendation to avoid problems with the packages. Packages
at the beginning of the session, they must be charged since, at times, there may be conflicts
between along the same user-defined functions and the that defines the package to be
loaded into memory.
As we have seen, to identify the symbols that define who they are themselves
Mathematica, it is preferable to assign them names that start with lowercase. Most of the
functions of Mathematica are written in C. However, some functions, such as join or
Laplace are written in the same Mathematica. The functions written in Mathematica are
those that are stored in packages. About 130 packages are distributed with version 2.2. They
cover areas such as algebra, calculus, discrete mathematics, geometry, graphs, linear
algebra, theory of numbers, numerical calculus or statistics.
But in addition to own packages distributed with Mathematica, the user can set and save
their own packages.
A package is a file that contains definitions of Mathematica (programs). Packages make
it possible to:
Create a function or collection of functions for later use.
MATRIX ALGEBRA
2.1 VECTORS
Mathematica allows you to work with vectors through the following functions:
Table [f {, n}] builds the n-dimensional vector whose elements are the
result of evaluating the function f in paragraphs i = 1,2,3, n
Array [a, n] builds the n-dimensional vector {[1], [2],, [n]}
Range [n] builds the n-dimensional vector {1, 2,, n}
Range [n1, n2] builds the vector {n1, n1 + 1,, n2}
Range [n1, n2, dn] builds the vector {n1, n1 + dn,, n2}
list [[i]] or Part [list, i] extracts the element list vectro i-th
Lenght [list] gives the number of elements in the vector list
ColumnForm [list] shows the elements of the vector list in column
Below are examples
In [1]: = Table [Exp, {i, 3}]
{Exp, Exp, Exp}
In[2]:= Table[Exp[2 i], {i, 3}]
2 4 6
{E , E , E }
In[3]:= Table[Exp[2 i], {i, 3}]//N
{7.38906, 54.5982, 403.429}
In[4]:= Array[b, 3]
{b[1], b[2], b[3]}
In[5]:= Range[5]
{1, 2, 3, 4, 5}
In[6]:= Range[7, 13]
{7, 8, 9, 10, 11, 12, 13}
In[7]:= Range[7, 13, 2]
{7, 9, 11, 13}
In[8]:= ColumnForm[%]
7
9
11
13
In[9]:= Length[%%]
4
In[10]:= {1, 2, 3, 4, 5}[[3]]
3
In[11]:= Part[{a,b,c,d,e}, 3]
C
2.2 OPERATIONS WITH VECTORS
Following are the rules from the usual operations in Mathematica with scalars and
vectors:
{a, b} + {c, d} = {a + c, b + d}
{a, b} - {c, d} = {a - c, b - d}
{a, b}. {c, d} = ac + bd
p + {a, b} = {p, p+b} where p is a scalar
The product of scalar vector is expressed using the operator *. We will have:
to * {x, and} = {ax, ay}
{a, b, c} * {x, y, z} = {ax, by, cz}
In general, you can apply a function f to the components of a vector. We will have:
f [{a, b, c}] = {f (a), f (b), f (c)}
Here below some examples
We define the array of elements = a11, a12 = b, a21 = c and a22 = d, to then choose the
vector corresponding to the second row and its term (2.1).
In [1]:=r={{a,b},{c,d}}
{{a, b}, {c, d}}
In [2]: = r [[2]]
{c, d}
In [3]: = r [[2.1]]
c
Now we define the vector s =(x,y) and multiply it by the scalar p, then add it to the
vector (z, t)
In[4]:= s={x,y}
{x, y}
In[5]:= p*s
{p x, p y}
In[6]:= s+{z,t}
{x + z, t + y}
Now defines the vector u =(e,f) and signal is multiplied by the vector s. subsequently
matrix r is multiplied by the vector u, the vector s and herself
In[7]:= u={e,f}
{e, f}
In[8]:=u.s
e x + f y
In [9]: = r.u
{a e +b f, c e + d f}
In[10]:= r.s
{a x + b y, c x + d y}
In[11]:= r.r
2 2
{{a + b c, a b + b d}, {a c + c d, b c + d }}
Now the vector s is multiplied by the matrix r, and the vector u is put as a factor on both
sides of the r matrix. Finally multiplies the scalar p vector u and joins the scalar q
In[12]:= s.r
{a x + c y, b x + d y}
In[13]:=u.r.u
e (e + c f) + f (b e + d f)
In[14]:= p*u+q
{e p + q, f p + q}
Now multiply a scalar by a matrix, is a combination of two linear vectors , and
applies the function cosine to a vector
In [1]: = p * {{a, b}, {c, d}}
{{a p, b p}, {c p d p}}
In [2]: = c * {x, and} + d * {z, t}
{c x + d z, d t + c and}
In[3]:= Cos[{Pi/4,Pi,Pi/2}]
1
{-, -1, 0}
SQRT [2]
2.3 MATRICES
The matrix:
|a11 a12 a13.. a1n|
|a21 a22 a23 . a2n|
A = (aij)= |a31 a32 a33 . a3n| i=1,..,m j=1,,n
| |
|am1 am2 am3 . amn|
It is expressed in Mathematica as follows:
A= {{a[1,1], a[1,2],, a[1,n]}, {a[2,1], a[2,2],, a[2,n]},
{a[m,1], a[m,2],, a[m,n]}}
Mathematica uses the following basic functions for working with arrays:
Table [f, {i, m}, {j, n}] builds the resulting (mxm) matrix of the evaluation
of f with i ranging from 1 to m and j ranging from 1 to n.
Array [a, {m, n}] builds the dimensions (mxm) matrix, whose term
i, j-th is a[i, j].
Matrix [[i]] or Part [matrix, i]
extracts the row i-th of the matrix.
Matrix [[I,j]] or Part [matrix, I, j]
extracts the element i, j-th of the matrix.
Dimensions [matrix] returns the dimensions of the matrix
MatrixForm [MatrizLista] gives in an array the array expressed in form of list
MatrizLista.
Some examples of these functions are:
In[1]:= A=Array[a,{3,4}]
{{a[1, 1], a[1, 2], a[1, 3], a[1, 4]},
{a[2, 1], a[2, 2], a[2, 3], a[2, 4]},
{a[3, 1], a[3, 2], a[3, 3], a[3, 4]}}
In[2]:= MatrixForm[A]
a[1, 1] a[1, 2] a[1, 3] a[1, 4]
a[2, 1] a[2, 2] a[2, 3] a[2, 4]
a[3, 1] a[3, 2] a[3, 3] a[3, 4]
In[3]:= B=Table[i+j,{i,4},{j,3}]
{{2, 3, 4}, {3, 4, 5}, {4, 5, 6}, {5, 6, 7}}
In[4]:= MatrixForm[B]
2 3 4
3 4 5
4 5 6
5 6 7
In[5]:= Array[a, {4,3}]
{{a[1, 1], a[1, 2], a[1, 3]},
{a[2, 1], a[2, 2], a[2, 3]},
{a[3, 1], a[3, 2], a[3, 3]},
{a[4, 1], a[4, 2], a[4, 3]}}
In[6]:= MatrixForm[%]
a[1, 1] a[1, 2] a[1, 3]
a[2, 1] a[2, 2] a[2, 3]
a[3, 1] a[3, 2] a[3, 3]
a[4, 1] a[4, 2] a[4, 3]
In[7]:= %+B
{{2 + a[1, 1], 3 + a[1, 2], 4 + a[1, 3]},
{3 + a[2, 1], 4 + a[2, 2], 5 + a[2, 3]},
{4 + a[3, 1], 5 + a[3, 2], 6 + a[3, 3]},
{5 + a[4, 1], 6 + a[4, 2], 7 + a[4, 3]}}
In[8]:= %%-B
{{-2 + a[1, 1], -3 + a[1, 2], -4 + a[1, 3]},
{-3 + a[2, 1], -4 + a[2, 2], -5 + a[2, 3]},
{-4 + a[3, 1], -5 + a[3, 2], -6 + a[3, 3]},
{-5 + a[4, 1], -6 + a[4, 2], -7 + a[4, 3]}}
In[9]:= A[[2]]
{a[2, 1], a[2, 2], a[2, 3], a[2, 4]}
In[10]:= B[[2,3]]
5
In[11]:= Part[B,3]
{4, 5, 6}
In[12]:= Part[B,2,3]
5
In[13]:= Dimensions[B]
{4, 3}
In [13]: = [A] Dimensions
{3, 4}
2.4 OPERATIONS WITH MATRICES
Mathematica has to work with arrays, the following functions:
A + B sum of matrices A and B
A - B substraction of the matrices A and B (A minus B)
c M product of the scalar c by the matrix M
A. B product of the matrices A and B (A B)
-1
Inverse [A] inverse matrix (A)
n
MatrixPower [A, n] power n-th of the matrix A (A)
Det [A] calculates the determinant of the matrix A
Transpose [A] calculates the transposed matrix from the matrix A
IdentityMatrix [n] generates the identity matrix of order n
DiagonalMatrix [list]
It generates the diagonal matrix whose diagonal elements are the
elements of the list
Eigenvalues [A] calculates the eigenvalues of the matrix A
Eigenvalues [N [A]] calculates the numerical eigenvalues of a.
Eigenvectors [A] calculates the eigenvectors of the matrix A
Eigenvectors [N [A]]
calculates the numeric eigenvectors of the matrix A
Below are examples presentanm:
In[1]:=M=Table[1/(i+j+1), {i,3}, {j,3}]
1 1 1 1 1 1 1 1 1
{{-, -, -}, {-, -, -}, {-, -, -}}
3 4 5 4 5 6 5 6 7
In[2]:=MatrixForm[M]
1 1 1
- - -
3 4 5
1 1 1
- - -
4 5 6
1 1 1
- - -
5 6 7
In[3]:= Transpose[M]
1 1 1 1 1 1 1 1 1
{{-, -, -}, {-, -, -}, {-, -, -}}
3 4 5 4 5 6 5 6 7
In[4]:= P=Inverse[M]
{{300, -900, 630}, {-900, 2880, -2100},
{630, -2100, 1575}}
In[5]:= P . M
{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}
In[6]:= MatrixForm[%]
1 0 0
0 1 0
0 0 1
In[7]:= Eigenvalues[M]
71 1/3
{ + (369995 2 ) /
315
(7 Power[29266533144000000 +
Power[29266533144000000 +
1/3 71
(1134000 2 ), -
315
(369995 (1 + I Sqrt[3])) /
2/3
(7 2 Power[29266533144000000 +
6889050000000 I Sqrt[102103], 1/3]) -
((1 - I Sqrt[3]) Power[29266533144000000 +
6889050000000 I Sqrt[102103], 1/3]) /
1/3 71
(2268000 2 ), -
315
(369995 (1 - I Sqrt[3])) /
2/3
(7 2 Power[29266533144000000 +
1/3
(2268000 2 )}
In[8]:= Eigenvalues[N[M]]
{0.657051, 0.0189263, 0.000212737}
In[9]:= Eigenvectors[N[M]]
{{-0.703153, -0.549268, -0.451532},
{-0.668535, 0.29444, 0.68291},
{0.242151, -0.782055, 0.574241}}
In[10]:= Det[M]
1
378000
In[11]:= MatrixPower[M,3]
10603 1227 26477 1227 10783 74461
{{, , }, {, , -},
75600 11200 294000 11200 126000 1058400
26477 74461 8927
{, -, }}
294000 1058400 154350
In[12]:= MatrixForm[%]
10603 1227 26477
75600 11200 294000
1227 10783 74461
-
11200 126000 1058400
26477 74461 8927
-
294000 1058400 154350
In[13]:= DiagonalMatrix[{1,2,3,4,5}]
{{1, 0, 0, 0, 0}, {0, 2, 0, 0, 0}, {0, 0, 3, 0, 0}, {0, 0, 0, 4, 0}, {0, 0, 0, 0, 5}}
In[14]:= MatrixForm[%]
1 0 0 0 0
0 2 0 0 0
0 0 3 0 0
0 0 0 4 0
0 0 0 0 5
In[15]:= IdentityMatrix[4]
{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}
In[16]:= MatrixForm[%]
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
In[17]:= R=Table[1/i+j-1,{i,3},{j,3}]
1 3 5 1 4 7
{{1, 2, 3}, {-, -, -}, {-, -, -}}
2 2 2 3 3 3
In[18]:= 6 R
{{6, 12, 18}, {3, 9, 15}, {2, 8, 14}}
In[19]:= R+M
4 9 16 3 17 8 8 3 52
{{-, -, }, {-, , -}, {, -, }}
3 4 5 4 10 3 15 2 21
In[20]:= R-M
2 7 14 1 13 7 2 7 46
{{-, -, }, {-, , -}, {, -, }}
3 4 5 4 10 3 15 6 21
In[21]:= R . M
In[22]:= M . R
Table [Random [], 0, {m}, {n}] defines array of random integers of dimensions
(mxn)
Table[If[i >= j, 1, 0], {i,m}, {j,n}] defines a lower unit triangular matrix
Table[If[i >= j, a, 0], {i,m}, {j,n}] defines a lower triangular matrix, whose non-
zero terms are a
Table[If[i <= j, 1, 0], {i,m}, {j,n}] defines a upper unit triangular matrix
Table[If[i <= j, a, 0], {i,m}, {j,n}] defines an upper triangular matrix, whose non-
zero terms are a
M[[{i1,, ir}, {j1,, jr}]] defines the subarray of M with dimensions
rxs, formed by the rows i1,, is and columns j1,, js.
M[[Range[i0, i1], Range[j0, j1]] defines the subarray whose rows comes given by
ranks between i0 and i1, and whose columns are given
through the ranks included between j0 and j1.
VectorQ [expression] gives True if the expression is a vector, and
false otherwise.
MatrixQ [expression] gives True if expression is an array and
false otherwise.
V.V, V.M, M.V, M.M, They represent the products between
vectors and matrices, being a matrix M and V a vector.
Minors [M, k] returns minors of order k (matrices of
dimension kxk) of the matrix M.
Sum [[M [i, i]], {i, Length [M]}] calculates the trace of the matrix M
M
MatrixExp [M] computes the matrix Exp [M] = E
Inverse [M, Modulus - > p] calculates the inverse of M p module
SingularValues [M] returns a list of vectors orthonormal U and
V, and the values of the diagonal of the diagonal matrix D
such that: M = UDV (the order list is {u, diagonal elements
of D, V})
Below are examples
In [1]: = SingularValues [N [{{1,2}, {1,2}}]]
{{{- 0.707107, - 0.707107}}, {3.16228},}
{{- 0.447214, - 0.894427}}}
In this example the matrix have decomposed into the product of the transpose of the
first vector in the list, the diagonal matrix whose two diagonal values are worth 3.16228
and latest list vector
In [2]: = SingularValues [N [{{1,3}, {- 4.3}}]]
{{{- 0.289784, - 0.957092}, {- 0.957092, 0.289784}},}
{5.14916,2.91309},
{{{0.687215, - 0.726454}, {- 0.726454, - 0.687215}}}
In this example we have found two solutions for the vectors U and V, and the diagonal
matrix D is the diagonal values 5.14916 and 2.91309.
Now we are going to find the inverse of a matrix module an integer and to check that
the process is correct
In[3]:= M={{2,4},{3,7}}
{{2, 4}, {3, 7}}
In[4]:= Inverse[M]
7 3
{{-, -2}, {-(-), 1}}
2 2
In[5]:= Inverse[M, Modulus -> 11]
{{9, 9}, {4, 1}}
In[6]:= Mod[M . %, 11]
{{1, 0}, {0, 1}}
In the following examples the power base and of a matrix M is calculated and
compared with the value of the development in series of the function E ^ M for the 50 first
terms (you will notice the coincidence)
In[7]:= MatrixExp[M]
(9 - Sqrt[73])/2
-((-5 - Sqrt[73]) E )
{{ +
2 Sqrt[73]
(9 + Sqrt[73])/2
(-5 + Sqrt[73]) E
,
2 Sqrt[73]
(9 - Sqrt[73])/2
(-5 - Sqrt[73]) (-5 + Sqrt[73]) E
- -
12 Sqrt[73]
(9 + Sqrt[73])/2
(-5 - Sqrt[73]) (-5 + Sqrt[73]) E
-}\
12 Sqrt[73]
(Sqrt 9 [73]) / 2 (9 + Sqrt [73]) / 2
-3 E 3 E
, { + -,
[73] Sqrt Sqrt [73]
(9 - Sqrt[73])/2
(-5 + Sqrt[73]) E
-
2 Sqrt[73]
(9 + Sqrt[73])/2
(-5 - Sqrt[73]) E
}}
2 Sqrt[73]
In[8]:= MatrixExp[M]//N
{{1338.93, 3019.58}, {2264.68, 5113.4}}
In[9]:= Sum[MatrixPower[M, i]/i!, {i, 0, 50}]//N
{{1338.93, 3019.58}, {2264.68, 5113.4}}
Then defines a matrix and its characteristic polynomial, child of order 2 and its trace is
calculated.
In[10]:= A=Table[1/(i+j), {i,3},{j,3}]
1 1 1 1 1 1 1 1 1
{{-, -, -}, {-, -, -}, {-, -, -}}
2 3 4 3 4 5 4 5 6
In[11]:= Det[A- x IdentityMatrix[3]]
2
1 131 x 11 x 3
- + - x
43200 3600 12
In[12]:= Minors[A,2]
1 1 1 1 1 1 1 1 1
{{, , }, {, , }, {, , }}
72 60 240 60 48 180 240 180 600
In [13]: = Sum [to [[i, i]], {i, 3}]
11
-
12
It will now define a matrix B and a vector to perform various including operations
In[14]:= B={{a,b},{c,d}}; v={x,y}; B . v
{a x + b y, c x + d y}
In[15]:= v . B
{a x + c y, b x + d y}
In[16]:= v . B . V
{a x + c y, b x + d y} . V
In[17]:= VectorQ[{a,b,c}]
True
In[18]:= MatrixQ[{{a,b,c},{p,q}}]
False
13 -10 -4
14 -5 -10
-5 11 13
In[3]:= MatrixForm[B-4 A]
-2 10 -29
-26 -5 5
-30 1 8
In[4]:= MatrixForm[Inverse[A.B]]
59 53 167
-()
380 190 380
223 92 979
-() -()
570 95 570
49 18 187
-()
114 19 114
In[5]:= MatrixForm[Transpose[(A-B).B]]
-198 10 218
158 -1 -154
217 -5 -218
In[6]:= MatrixForm[MatrixPower[A,2]]
2 -2 32
9 -38 37
36 -18 20
In[7]:= MatrixForm[Exp[B]]
10 -6 -9
E E E
6 -5 -7
E E E
-10 9 12
E E E
In [8]: = Det [MatrixPower [B, 3]]
216
In[9]:= NSolve[Det[A-x IdentityMatrix[3]]==0, x]
{{x -> -1.13762 - 5.38363 I},
{x -> -1.13762 + 5.38363 I}, {x -> 6.27524}}
Exercise 2-2 Given the vectors v = (0,5,1,2) and w = (3,0,4,-2), calculate v-2w,
the dot product of v by w and normalize both vectors.
In[1]:= v={0,5,1,2}; w={3,0,4,-2}; v-2w
{-6, 5, -7, 6}
In[2]:= v.w
0
In[3]:= v/Sqrt[v.v]
5 1 2
{0, Sqrt[-], , Sqrt[]}
6 Sqrt[30] 15
In[4]:= w/Sqrt[w.w]
3 4 -2
{, 0, , }
[29] [29] Sqrt Sqrt Sqrt [29]
2.6 DECOMPOSITION OF MATRICES
Mathematica enables features that enable decomposition product of vectors orthogonal
matrices and diagonal matrices. We have already seen how the function
SingularValues[M], decompose the matrix M in the products U.D.V, where D is a
diagonal matrix and U and V are vector orthonormal. The function PseudoInverse[M]
calculates the inverse of the matrix M in terms of the matrices U, D and V. On the other
hand, also Mathematica allows the QR Decomposition of a matrix M. This decomposition
is to find an orthonormal matrix Q and a matrix triangle R, such that M = Qt. R (Qt is the
transposed matrix of Q).
In addition, can also get the Schur decomposition of a square matrix M. This
decomposition is to find an orthogonal matrix Q and a upper triangular matrix T, such that
M = QTQt.
We also have the LinearAlgebra Cholesky package, which enables the function
CholeskyDecomposition[M], permitting decomposing the symmetric matrix defined
positive M, product of an upper triangular matrix Q and its transpose. M = Qt. Q
Mathematica also offers the posibility to decompose a matrix in Jordan canonical form.
If A is a matrix of order nxn, then there is an invertible matrix C such that C -1 A C = J,
where J is a Jordan matrix with the eigenvalues of A in the diagional. The matrix J is
called Jordan canonical form.
In [3]: = MatrixForm [%]
1 0 0 - 2 0
0 1 0 - 2 0
0 0 1 - 2 0
0 0 0 0 1
0 0 0 0 0
The rank of the array is 4, because the previous triangular matrix has 4 non-zero rows
In [4]: = NullSpace [A]
{{2, 2, 2, 1, 0}}
If A is the matrix of a linear transformation, the core of the application would be of
dimension 1 and the image would have dimension 3
In [5]: = B = {{2.3, - 1, 3, 0}, {1,2,1,-2,1}, {3,5,0,1,1}, {2.1, - 7, 17, - 4}}
{{2, 3, - 1, 3, 0}, {1, 2, 1, - 2, 1}, {3, 5, 0, 1, 1}, {2, 1, - 7, 17, - 4}}
In [6]: = MatrixForm [RowReduce [B]]
1 0 - 5 12 - 3
0 1 3 - 2 7
0 0 0 0 0
0 0 0 0 0
The rank of the array B is 2, because the previous matrix has 2 rows not null
In [7]: = NullSpace [B]
{{3, - 2, 0, 0, 1}, {- 12, 7, 0, 1, 0}, {5, - 3, 1, 0, 0}}
2.8 SEMEJANT MATRICES AND DIAGONALIZATION
Two matrices A and B dimensions (m,n) are equivalent, if there are two regular
matrices U and V, such that A = UBV. Mathematica SingularValues[A] function calculates
a diagonal matrix Md which is equivalent to A.
Two square matrices of order n, A and B, are congruent if there is a regular matrix P
such that A = PBPt or A = PtBP. The Mathematica function SchurDecomposition[A]
computes a matrix T that is congruent with A.
It is said that two arrays square of order n, A and B are semejant (similar) if exist an
invertible matrix P, called step matrix, such as:
A = PBP- 1
A matrix A is diagonalizable if it is similar to a diagonal matrix D, that is, if there is a
matrix of step P regulate, such as: A = PDP- 1. The process of calculation of the diagonal
matrix D and step matrix P is called Diagonalization of A.
Given a matrix to square of order n of real numbers, if all the eigenvalues (A
eigenvalues) are real and different then A is diagonalizable. The matrix D will have the
eigenvalues of A as the diagonal elements. Step P matrix is columns to the eigenvectors of
A corresponding to their own values. If the matrix A has eigenvalues r with multiplicity
greater than 1, will be diagonalizable if the kernel of the matrix A - r * In has dimension
equal to the degree of multiplicity of the eigenvalue r.
Mathematica provides the function JordanDecomposition[A] that diagonaliza matrix,
calculating the matrix step P.
Office 2-7. Diagonalizar the symmetric matrix whose rows are vectors:
(3, - 1, 0), (- 1, 2 - 1), (0, - 1, 3)
Find step P matrix, check the result and see that the eigenvalues of the initial
matrix are the elements of the diagonal of the matrix similar to the one given.
In [1]:=A={{3,-1,0},{-1,2,-1},{0,-1,3}}
{{3, - 1, 0}, {- 1, 2, - 1}, {0, - 1, 3}}
We are going to find the characteristic equation to calculate the eigenvalues of the
matrix A
In[2]:= B=A - x IdentityMatrix[3]
{{3 - x, -1, 0}, {-1, 2 - x, -1}, {0, -1, 3 - x}}
In[3]:= Solve[Det[B]==0,x]
{{x - > 1}, {x - > 3}, {x - 4}}
We have already calculated the eigenvalues of A (we could also have used the
function Eigenvalues [A], but we used the characteristic equation to consider it later).
Since the eigenvalues are all different (of multiplicity 1), the matrix A is diagonalizable.
Now we calculate the diagonal matrix, j, similar to A, which will be the eigenvalues of
A diagonal, and the matrix of step j. To do this we use the JordanDecomposition function
In [4]: = {c, j} = JordanDecomposition [A]
{{{1, - 1, 1}, {2, 0, - 1}, {1, 1, 1}}, {{1, 0, 0}, {0, 3, 0}, {0, 0, 4}}}
In [5]: = MatrixForm [{c, j}]
1-2-1
-1 0 1
1 - 1-1
1 0 0
0 3 0
0-0-4
We now see that A and j are similar
In[6]:= Inverse[c].A.c
{{1, 0, 0}, {0, 3, 0}, {0, 0, 4}}
In[7]:= c.j.Inverse[c]
{{3, - 1, 0}, {- 1, 2, - 1}, {0, - 1, 3}}
Effectively A and j are similar.
Office 2-8. Find a diagonal matrix similar to the matrix whose rows are:
(7, - 2, 1), (- 2, 10 - 2), (1, - 2, 7)
In [1]: = H = {{7, - 2, 1}, {- 2, 10 - 2} {1, - 2 7}}
{{7, - 2, 1}, {- 2, 10 - 2} {1, - 2 7}}
In [2]: = Solve [Det [H - x * IdentityMatrix [3]] == 0, x]
{{x - > 6}, {x - > 6}, {x - 12}}
The matrix H is an eigenvalue of multiplicity 1 and another of multiplicity 2. H to be
diagonalizable, the kernel of the matrix A-6 I must have dimension equal to the degree of
multiplicity of the eigenvalue 6, which is 2.
In[3]:= {v1[x_],v2[x_],v3[x_]}=H - x IdentityMatrix[3]
{{7 - x, -2, 1}, {-2, 10 - x, -2}, {1, -2, 7 - x}}
In[4]:= M1 ={v1[6],v2[6],v3[6]}
{{1, -2, 1}, {-2, 4, -2}, {1, -2, 1}}
In[5]:= NullSpace[M1]
{{- 1, 0, 1}, {2, 1, 0}}
As the core of the nucleus of M1 has two vectors, its dimension is 2, which coincides
with the multiplicity of the eigenvalue 6. Therefore, the H matrix is diagonalizable, and
we can calculate the matrix j1 similar to frasaco, for an array of pass c1 we will also
calculate
In[6]:= {c1,j1}=JordanDecomposition[H]
{{{-1, 2, 1}, {0, 1, -2}, {1, 0, 1}}, {{6, 0, 0}, {0, 6, 0}, {0, 0, 12}}}
In[7]:= MatrixForm[%]
-1 0 1
2 1 0
1 -2 1
6 0 0
0 6 0
0 0 12
In[8]:= Inverse[c1].H.c1
{{6, 0, 0}, {0, 6, 0}, {0, 0, 12}}
In[9]:= c1.j1.Inverse[c1]
{{7, - 2, 1}, {- 2, 10 - 2} {1, - 2 7}}
In [10]: = MatrixForm [%]
7 - 2-1
-2 10 - 2
1-2-7
We have already tested the similarity between j1 and H.
Chapter 3.
1 11
-
0 1 0 5 5
2 7
-(-) -(-)
0 0 1 5 5
0 0 0 0 0
The rank of the array is 3, then the requested dimension is 3
To find a base is considered any lower order nonzero matrix 3. The vectors containing
components included in this minor will form a basis
In [2]: = Det [{2,3,4}, {3,4,7}, {0,5,5}]
-15
Then a base of the generated linear variety is the set of vectors:
{{2,3,4,-1,1},{3,4,7,-2,-1},{0,5,5,-1,4}}
Exercise 3-3. Given the set of vectors:
{{2,3, - 1}, {0,0,1}, {2,1,0}}
3
Study if they form a basis of R, and get the components of the vector x = (3,5,1)
on that basis.
In [1]: = Det [{{2.3, - 1}, {0,0,1}, {2,1,0}}]
4
Since we have three vectors in a space of dimension 3, they will form a basis if its
determinant is nonzero (linearly independent). Then they really form a basis.
The components of the vector (3,5,1) on that basis we are considering:
In [2]: = Inverse [{{2,0,2}, {3,0,1}, {- 1, 1, 0}}]. {3,5,1}
7 11 1
{-, , -(-)}
4 4 4
{{1,0,0},{1,0,1},{1,1,p}}
3
Study if they form a basis of R for any value of p
Exercise 3-5. Consider the bases B and B of the three-dimensional real vector
space:
B = {{1,0,0}, {- 1, 1, 0}, {0,1, - 1}}
B= {{1,0, - 1}, {2,1,0}, {- 1, 1, 1}}
Find the matrix of change of basis of B to B and calculate the components of
the vector {2,1,3} in base B, in the base B.
In[1]:= B={{1,0,0},{-1,1,0},{0,1,-1}};
B={{1,0,-1},{2,1,0},{-1,1,1}};
In[2]:= A=Inverse[Transpose[B]].Transpose[B]//MatrixForm
1 3 5
-(-) - -
2 2 2
1 1 1
- -(-) -(-)
2 2 2
1 3 3
-(-) - -
2 2 2
In[3]:= X={2,1,3};
In[4]:= X=Inverse[Transpose[B]].Transpose[B].X
{8, - 1, 5}
In[3]:=MatrixForm[%]//N
2.71828 1. 1.
0.367879 2.71828 1.
1. 0.367879 2.71828
1. 1. 2.71828
In [5]: = T1 [{1,1,2}]
{1, 0, 1, 2}
Exercise 3-14. We consider the linear transformation f between two vector
subspaces U and V of real three-dimensional space, so that f(a,b,c) =(a+b,b+c,a+c)
being (a, b, c) anywhere in U.
Find the matrix associated with the application f and (f)^5.
In[1]:= T3[{a_,b_,c_}]={a+b,b+c,a+c};
To find the f matrix we must consider the vector transformed by the canonical basis f
In [2]: = T3 [{1,0,0}]
{1, 0, 1}
In [3]: = T3 [{1,1,0}]
{2, 1, 1}
In [4]: = T3 [{1,1,1}]
{2, 2, 2}
The traspose of the matrix whose rows are found vectors, is the matrix of the linear
transformation f
In [5]: = Transpose [{{T3 [{1,0,0}]}, {T3 [{1,1,0}]}, {T3 [{1,1,1}]}}] / /
MatrixForm
1-2-2
0 1 2
1 1 2
In [6]: = MatrixPower [{{1,2,2}, {0,1,2}, {1,1,2}}, 5] //MatrixForm
197 334 566
116 197 334
167 283 480
Exercise 3-15. We consider the linear transformation f between two vector
subspaces U (contained in R^3) and V (contained in R^4), so that f(a,b,c) =(a,0,c,0)
being (a, b, c) anywhere in U.
Find the matrix associated to the application f, its kernel and the dimensions of
the kernel and the image of f.
In [1]: = T4 [{a_, b_, c_}] = {a, 0, c, 0};
In [2]: = A4 = Transpose [{{T4 [{1,0,0}]}, {T4 [{0,1,0}]}, {T4 [{0,0,1}]}}]
{{{1, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 1, 0}}}
In [3]: = B4 = MatrixForm [%]
1 0 0
0 0 0
0 0 1
0 0 0
The core is the set of vectors of U with null image v
In[4]:= Solve[T4[{a,b,c}]=={0,0,0,0},{a,b,c}]
{{a - > 0, c - > 0}}
So the core will be the set of vectors {0, b, 0} with varying u b. Moreover, obviously
the core has dimension 1, being a basis vector {0,1,0}.
The dimension of the image of f is 2, since the sum of the dimensions of the core and
the image must be the dimension of U (which is 3, as a subspace of R ^ 3). On the other
hand the dimension of the image of f must match the rank of the matrix of the linear
transformation, which is 2. The two vectors column containing the elements of the non-
null child which defines the rank of the array will form a basis of the image of f
In [5]: = Det [{{1.0}, {0,1}]
1
Then the image of f base will be {{1,0,0,0},{0,0,1,0}}
Exercise 3-16. We consider the bilinear form f:UxV - > R, being U and V two
vector subspaces of the three-dimensional real space, in such a way that:
f [{{x 1, x 2, x 3}, {y1, y2, y3}}] = x 1 y1-2 x 1 + 4 x 2 y3 - y2 x 3 y1-3 x 3 y3
Find the matrix associated with the bilinear form f and classify it.
In [1]: = T [{{x1_, x2_, x3_}, {y1_, y2_, y3_}}] = x 1 y1 - 2 x 1 y2 + 4 x 2 y3 - y1-3 3 x x
3 y3
x 1 y1 - y1-3 x - 2 x 1 y2 + 4 x 2 y3 - 3 x 3 y3
In [2]: = {x 1, x 2, x 3}. {{1, - 2, 0}, {0,0,4}, {- 1, 0, 3}}. {y1, y2, y3} //Expand
x 1 y1 - y1-3 x - 2 x 1 y2 + 4 x 2 y3 + 3 x 3 y3
Then the f matrix is {{1, - 2, 0}, {0,0,4}, {- 1, 0, 3}}
In [3]: = Det [{{1, - 2, 0}, {0,0,4}, {- 1, 0, 3}}]
8
As the determinant of the matrix of f is non-null, the bilinear form is regular not
degenerada.
3.3 QUADRATIC FORMS
Exercise 3-17. Consider the quadratic form f:u - > R, being U vector subspace of
the real three-dimensional space, in such a way that:
2 2 2
f [{x, y, z}] = x - 2 x y + y + 6 x z - 3 y z +4 z
Find the matrix associated to f and classify it.
In [1]: = {x, y, z}. {{1, - 1, 3}, {- 1, 1, - 3/2}, {3, - 3/2.4}}. {x, y, z} //Expand
2 2 2
x - 2 x y + y + 6 x z - 3 y z + 4 z
Then the f matrix is {{1, - 1, 3}, {- 1, 1, - 3/2}, {3, - 3/2.4}}
To classify it, we find the corresponding determinants
In [2]: = Det [{{1, - 1, 3}, {- 1, 1, - 3/2}, {3, - 3/2.4}}]
9
-(-)
4
In [3]: = Det [{{1, - 1}, {- 1, 1}}]
0
The quadratic form is semidefinida negative.
But the classification can also be done through the eigenvalues of the matrix of the
quadratic form.
A quadratic form is defined positive if and only if all its eigenvalues are strictly
positive. A quadratic form is defined to be negative if and only if all its eigenvalues are
strictly negative.
A quadratic form is semidefinida positive if and only if all its eigenvalues are non-
negative. A quadratic form is semidefinida negative if and only if all its eigenvalues are
not positive.
A quadratic form is undefined if there are positive and negative eigenvalues
In [4]: = Eigenvalues [N [{{1, - 1, 3}, {- 1, 1, - 3/2}, {3, - 3/2.4}}]]
{6.4498 - 0.856906, 0.407101}
All the eigenvalues are not positive, with what is the quadratic is semidefinida negative
Exercise 3-18. Consider the quadratic form f:u - > R, being U vector subspace of
the real three-dimensional space, in such a way that:
2 2 2
f[{x,y,z}]=x + 2 y + 4 y z + 2 z
Find the matrix associated to f and classify it. Find your reduced equation, its
range and its document.
In [1]: = ({x, y, z}. {}) {1,0,0},{0,2,2},{0,2,2}}). {x, y, z} //Expand
2 2 2
x + 2 y + 4 y z + 2 z
Then the array is {{1,0,0},{0,2,2},{0,2,2}}
In [2]: = Det [{{1,0,0}, {0,2,2}, {0,2,2}}]
0
In [3]: = Det [{{1.0}, {0.2}}]
2
The quadratic form is positive semidefinite and degenerate.
To find the reduced equation, we make the diagonalizaion of the matrix, and find the
expression using the diagonal matrix
In [4]: = JordanDecomposition [{{1,0,0}, {0,2,2}, {0,2,2}}] //MatrixForm
0 - 1-1
1 0 0
0 1 1
0 0 0
0 1 0
0-0-4
In [5]: = ({a, b, c}. {}) {0,0,0},{0,1,0},{0,0,4}}). {a, b, c}
2 2
b + 4 c
2 2
f(a,b,c) = b + 4 c is reduced as the quadratic equation.
The range of the quadratic form is 2, since the rank of the array is 2. The document also
is 2, since the number of positive terms in the diagonal of the matrix diagonalizada is 2.
4Chapter 4.
b - c
{{x -> -()}}
a
In[2]:= Solve[x^2 + a x + 2 == 0, x]
2 2
-a - Sqrt[-8 + a ] -a + Sqrt[-8 + a ]
{{x -> }, {x -> }}
2 2
In[3]:= Solve[E^(a x) == 1,x]
Solve::ifun:
Warning: Inverse functions are being used by Solve,
so some solutions may not be found.
{{x - > 0}}
In addition, when an equation contains a feature not explicitly, program returns the
solution generic equation in abstract terms of the function, as shown in the following
example:
In[1]:= Solve[f[x]==2,x]
(- 1)
{{x - > f [2]}}
Mathematica can also solve equations with subsidiary conditions. The most notable
application are the equations subject to the prerequisite of trigonometry, trigonometric
(SIN (x) ^ 2 + Cos (x) ^ 2 = 1).
Here are some examples
In [1]: = condition = Sin [x] ^ 2 + Cos [x] ^ 2 == 1
2 2
COS [x] + Sin [x] == 1
In [2]: = Solve [{Sin [x] + 2 Cos [x] == 1, condition}, {no [x], Cos [x]}]
3 4
{{Sin[x] -> -(-), Cos[x] -> -},
5 5
{Sin[x] -> 1, Cos[x] -> 0}}
In [3]: = Solve [{Sin [x] == Cos [x], condition}, {no [x], Cos [x]}]
1 1
{{Sin[x] -> -(-), Cos[x] -> -(-)},
Sqrt[2] Sqrt[2]
1 1
{Sin[x] -> -, Cos[x] -> -}}
Sqrt[2] Sqrt[2]
It is also possible to give solutions of an equation module p. The command that enables
Mathematica is as follows:
Solve [equation & & Modulus == p, variable]
Resolves the specified equation, for the specified variable, but module p.
Here are some examples
In [1]: = Solve [5 + 11 x + 17 x ^ 2 + 7 x ^ 3 + 16 x ^ 4 + x ^ 5 == 0 & & Modulus ==
19, x]
{{Modulus - > 19, x - > - 18}, {Modulus - > 19, x - > - 16},}
{Modulus - > 19, x - > - 12}, {Modulus - > 19, x - > - 7},
{Modulus -> 19, x -> -1}}
In[2]:= Solve[x^4-1==0&&Modulus==5,x]
{{Modulus -> 5, x -> -4}, {Modulus -> 5, x -> -3},
{Modulus -> 5, x -> -2}, {Modulus -> 5, x -> -1}}
4.2 SPECIAL COMMANDS TO SOLVE EQUATIONS
The command reduces Mathematica to solve equations symbolically as follows:
Reduce [equation, variable]
Simplifies everything in the given variable equation and considers its
solutions, both in terms of the given variable, and in terms of possible
parameters included in the equation. It also offers solutions with logical
links including.
Below are examples.
In[1]:= Reduce[a x == 0, x]
to == 0 | x == 0
We see how, apart from considering the solution in the variable x (x = 0), is also
considered the possible solution (a = 0) in terms of the parameter to. We also noted the use
of the logical union (|) in the final form of the solutions
In[2]:= Reduce[E^(a x) == 1,x]
Reduce::ifun:
Warning: Inverse functions are being used by Solve,
so some solutions may not be found.
a x
Log[E ] == 0 && a == 0 || a != 0 && x == 0
Reduce[a x +b ==c, x]
-b + c
b == c && a == 0 || a != 0 && x ==
a
In this case, the program tells us, firstly, that there may be more solutions than those
presented. Then presents the solutions linked by logical links. The first solution is b = c
and a = 0 (uses the logical disjunction symbol & &). It is also a solution to 0 and x =(c-b)
/a (note that in Mathematica different symbol is ! =).
In[3]:= Reduce[x^2 + a x + 2 == 0, x]
2 2
-a - Sqrt[-8 + a ] -a + Sqrt[-8 + a ]
x == || x ==
2 2
Other special command to solve polynomial equations of any degree is Roots, whose
syntax is as follows:
Roots [polinomialequation, variable]
As a result, it offers a list of solutions of the polynomial equation
considered, with respect to the given variable, linked by logical operators.
Here are some examples.
In [1]: = Roots [x ^ 2 + 3 x == 2, x]
-3 - Sqrt[17] -3 + Sqrt[17]
x == - || x == -
2 2
In[2]:= ToRules[%]
-3 - Sqrt[17] -3 + Sqrt[17]
Sequence[{x -> -}, {x -> -}]
2 2
The command ToRules translates the solutions given by the command Roots in the
form of logical expression, to solutions in the classical form of lists and rules.
Provided that Mathematica has problems when it comes to solving a polynomial
equation, it presents the solution according to the command Roots. If this solution is
rounded off with the command N, we obtain a final solutions form, as shown in the
following examples:
In[1]:= Solve[x^5+5x+1==0,x]
5
{ToRules[Roots[5 x + x == -1, x]]}
In[2]:= N[%]
{{x -> -1.0045 - 1.06095 I},
{x -> -1.0045 + 1.06095 I}, {x -> -0.199936},
{x -> 1.10447 - 1.05983 I},
{x -> 1.10447 + 1.05983 I}}
In[3]:= Solve[x^9+x^8+x^7==1,x]
2 4 6 7
{{x -> -I}, {x -> I}, ToRules[Roots[x - x + x + x == 1, x]]}
In[4]:= N[%]
{{x -> -1. I}, {x -> 1. I}, {x -> -0.943723 - 0.388391 Y},
{x -> -0.943723 + 0.388391 Y}, {x -> -0.619861 - 0.995101 I},
{x -> -0.619861 + 0.995101 I}, {x -> 0.628087 - 0.638417 I},
{x -> 0.628087 + 0.638417 I}, {x -> 0.870994}}
In[5]:= Roots[x^9+x^8+x^7==1,x]
2 4 6 7
x == I || x == -I || Roots[-1 + x - x + x + x ==
0, x]
In[6]:= N[%]
x == 1. I || x == -1. I ||
x == -0.943723 - 0.388391 I ||
x == -0.943723 + 0.388391 I ||
x == -0.619861 - 0.995101 I ||
x == -0.619861 + 0.995101 I ||
x == 0.628087 - 0.638417 I ||
x == 0.628087 + 0.638417 I || x == 0.870994
4.3 NUMERICAL METHODS FOR RESOLUTION OF
EQUATIONS
When an equation cannot be solved symbolically one can attend to their numeric
resolution approximated through the NSolve, whose syntax and the following command.
NSolve [polynomialequation, variable]
It gives the approximate numerical solutions of the polynomial equation
considered.
NSolve [polinomyalequation, variable, n]
It gives the approximate numerical solutions of the polynomial
equation considered, with n digits of precision. If n is not specified,
Mathematica takes as a value default of its variable WorkingPrecision.
Here are some examples
In [1]: = NSolve [x ^ 7 + x + 1 = 0, x]
{{x - > - 0.796544}, {x - > - 0.705298 - 0.637624 I},}
{x - >-0.705298 + 0.637624 I},
{x - > 0.123762 - 1.05665 I},
{x - > 0.123762 + 1.05665 I},
{x - > 0.979808 - 0.516677 I},
{x -> 0.979808 + 0.516677 I}}
In[2]:= NSolve[x^7 + x + 1 == 0, x, 20]
{{x -> -0.79654435412845710366},
{x -> -0.70529808793715023876 - 0.63762376980623151256 I},
{x -> -0.70529808793715023876 +0.63762376980623151256 I},
{x -> 0.123761880511477405916 - 1.05665001119707374961 I},
{x -> 0.123761880511477405916 +1.05665001119707374961 I},
{x -> 0.97980838448990138467 - 0.51667688383991207112 I},
{{x - > 0.97980838448990138467 + 0.51667688383991207112 I}}
In [3]: = NSolve [Sin [x] Cos [x] == 0, x]
Solve::ifun:
Warning: Inverse functions are being used by Solve,
so some solutions may not be found.
{{x - > 0.}, {x - > 1.5708}}
In [4]: = NSolve [x Sin [x] == 1/2, x]
Solve::tdep:
The equations appear to involve transcendental
functions of the variables in an essentially
non-algebraic way.
1
NSolve[x Sin[x] == -, x]
2
In the case of non-polynomial equations is used widely the FindRoot command, whose
syntax is as follows:
FindRoot [equation, {x, x0}]
Find the numerical solution for the considered equation, variable x,
taking as initial value for the iterative algorithm (Newton method) the
value x = x0.
FindRoot [equation, {x, {x0, x1}]
Look for the numerical solution for the considered equation, variable x,
taking as initial values for the iterative algorithm (the secant method) x =
x0 and x = x1 (used when the symbolic derivatives of the equation are not
defined).
FindRoot [equation, {x, x0, xmin, xmax}]
Searchs the numerical solution for the equation considered variable x,
taking as initial value for the iterative algorithm value x = x 0 and
stopping the process when x takes a value outside the range given by xmin
and xmax.
FindRoot starts the algorithm of iteration with the initial value given at the
entrance and gradually tries to hedge the value of the candidate solution as much as
possible. When the equation has several solutions, the command always returns the first
that is. This solution will depend on the point where the algorithm has begun.
Initially, FindRoot uses the algorithm of Newton, which is given by the expression
(n) X = X (n-1) - f (x (n-1)) / f(x (n-1)). It is very important, for the converegencia of the
method to the solution, choose the initial approximation x 0 (typically take a root
approximate graphical inspection). On the other hand, it is important that does not engulf
the derivative of the function at the points considered, since according to the algorithm we
would have indeterminations. It is also important that the function be derivable and
Mathematica can be found the symbolic derivative of the function.
When a problem of those cited above (no derivative or derived no calculable
symbolically or not derivable function) happens, the program uses the secant method to
approximate solutions of the equation. This method requires two initial values for the
approximation algorithm. If these two initial values are of opposite sign, around the
solution, it is often guaranteed the success of convergence.
The following options can be used with FindRoot:
AccuracyGoal: gives the degree of approximation to zero a number, so that it can be
considered effectively zero, in order to take a value as a solution of an equation. The
default value is Automatic.
WorkingPrecision: gives the number of digits of precision with which solutions are
obtained. The default value is the internal variable $MachinePrecision.
MaxIterations: It serves to set the maximum number of allowed iterations to find
the solution. The default value is 15.
Compiled: serves to compile function. The default value is True.
Here are some examples
In [1]: = FindRoot [x Sin [x] == 1/2, {x, 1}]
{x - > 0.740841}
We have obtained the solution of the equation that is closest to the considered initial
value, which is 1. The Newton method has been used
In [2]: = FindRoot [Sin [x] == 2, {x I}]
{x - > 1.5708 + 1.31696 I}
Mathematica solves the equations in the complex field and also supports complex initial
values.
In[3]:= FindRoot[Sin[x] == 0, {x, 6, Pi/2, 3 Pi}]
{x -> 6.28319}
In[4]:= FindRoot[Sin[x] == 0, {x, 3, Pi/2 , 2 Pi}]
{x - > 3.14159}
In these last two examples has been that you get different solutions for the same
equation, in the same range, depending on the considered baseline. The Newton method
always gives the first solution that is
In[5]:= FindRoot[Zeta[1/2 + I t] == 0, {t, {12, 13}}]
-7
{t - > 14.1347 - 4.42626 10 and}
In this case, the algorithm used is the secant method, for the considered function we
have problems with derivatives. Note that have been given two initial values as input
In [6]: = FindRoot [Zeta [1/2 + I t] == 0, {t, {12, 13}},]
[AccuracyGoal - > 10]
-11
{t - > 14.1347 + 1.79066 10 I}
To change the acuracidad the solution differs from the previous one, for the same
equation.
Exercise 4-1. Solve the following equation:
10 9 8 7 4 3 2
x - x - 3x +3x +2x - x - 7x +3x+3 = 0
First intantamos calculate the exact solutions.
In[1]:= p= x^10-x^9-3x^8+3x^7+2x^4-x^3-7x^2+3x+3
2 3 4 7 8 9 10
3 + 3 x - 7 x - x + 2 x + 3 x - 3 x - x + x
In[2]:= Solve[p == 0, x]
{{x -> 1}, {x -> -Sqrt[3]}, {x -> Sqrt[3]},
7
We get three exact solutions and seven others on the basis of the command Roots. We
get 10 solutions rounded using the function N
In [3]: = N [%]
{{x - > 1.}, {x - > - 1.73205}, {x - > 1.73205},}
{x - > - 0.868688 - 0.585282 I},
{x - >-0.868688 + 0.585282 I}, {x - > - 0.496292},
{x - > 0.0763556 - 1.14095 I}, {x - > 0.0763556 + 1.14095 I},
{{x - > 1.04048 - 0.56735 I}, {x - > 1.04048 + 0.56735 I}}
Also could have been used directly the Nsolve command to obtain 10 approximate
solutions, since its a polynomial equation
In[4]:= NSolve[p == 0, x]
In[1]:= Solve[x^6 == 1, x]
1/3
{{x -> -1}, {x -> 1}, {x -> -(-1) },
1/3 2/3 2/3
{{x - > (- 1)}, {x - >-(-1)}, {x - > (- 1)}}
Exercise 4-3. Finding fifth roots of complex number -1 +3i and the cube roots
of - 8.
First we find the exact cube roots of - 8
In[1]:= Solve[x^3 +8 ==0, x]
1/3 2/3
{{x -> -2}, {x -> 2 (-1) }, {x -> -2 (-1) }}
Now we are going to round the result
In[2]:= NSolve[x^3+8 == 0, x]
{{x -> -2.}, {x -> 1. + 1.73205 I},
{{x - > 1. - 1.73205 I}}
Now we calculate the exact fifth roots of complex number
In[3]:= Solve[x^5 == -1+Sqrt[3] I, x]
1/5
{{x -> (-1 + I Sqrt[3]) },
1/5 1/5
{x -> -((-1) (-1 + I Sqrt[3]) )},
2/5 1/5
{x -> (-1) (-1 + I Sqrt[3]) },
3/5 1/5
{x -> -((-1) (-1 + I Sqrt[3]) )},
4/5 1/5
{{x - > (- 1) (- 1 + I Sqrt [3]) }}
Exercise 4-4. Find in the complex field a solution of the equation Cos (Z) = 3
First of all we are trying to find an accurate solution
In[1]:= Solve[Cos[z] == 3, z]
Solve::ifun:
Warning: Inverse functions are being used by Solve,
so some solutions may not be found.
{{z - > ArcCos [3]}}
The program warns of the possible existence of other different solutions.
Now lets round up the previous solution
In [2]: = N [%]
{{z - > 1.76275 I}}
Could also have tried directly find solutions with the Nsolve command, to reach the
same result
In[3]:= NSolve[Cos[z] == 3, z]
Solve::ifun:
Warning: Inverse functions are being used by Solve,
so some solutions may not be found.
{{z - > 1.76275 and}}
Exercice 4-5. Solve the following irrational equations:
2
(Sqrt[x-1] -1) +2 == 2Sqrt[x-1]
Sqrt[1-x] + Sqrt[1+x] == a
2 2
COS [x] + Sin [x] == 1
In[2]:= Solve[{Sin[x]+Cos[x]==Sqrt[3]/2,cond},{Sin[x],Cos[x]}]
Sqrt[3] - Sqrt[5]
{{Sin[x] -> ,
4
4 Sqrt[3] + 4 Sqrt[5]
Cos[x] -> },
16
Sqrt[3] + Sqrt[5]
{Sin[x] -> ,
4
4 Sqrt[3] - 4 Sqrt[5]
Cos[x] -> }}
16
We see that, in fact, already have exact solutions, that will be the arc and the arc cosine
of the securities offered in the previous solution.
If we round off the results, we use the function N
In[3]:= N[%]
{{Sin[x] -> -0.126004, Cos[x] -> 0.99203},
{{Sin [x] - > 0.99203, Cos [x] - > - 0.126004}}
To calculate the final solutions rounded, proceed in the following way:
In [4]: = NSolve [Sin [x] ==-0.126004, x]
Solve::ifun:
Warning: Inverse functions are being used by Solve,
so some solutions may not be found.
{{x - > - 0.12634}}
In [5]: = NSolve [Sin [x] == 0.99203, x]
Solve::ifun:
Warning: Inverse functions are being used by Solve,
so some solutions may not be found.
{{x -> 1.44446}}
In[6]:= NSolve[Cos[x]==0.99203, x]
Solve::ifun:
Warning: Inverse functions are being used by Solve,
so some solutions may not be found.
{{x -> 0.126338}}
In[7]:= NSolve[Cos[x]==-0.126004, x]
Solve::ifun:
Warning: Inverse functions are being used by Solve,
so some solutions may not be found.
{{x - > 1.69714}}
In this way we obtained four basic solutions of the first quadrant of the trigonometric
equation.
Exercise 4-7. Solve the following trigonometric equation:
Sin [x] + Sin [3 x] = 0
First we tried the exact solution
In [1]: = Solve [Sin [3 x] + Sin [x] == 0, x]
Solve::tdep:
The equations appear to involve transcendental
functions of the variables in an essentially
non-algebraic way.
Solve [Sin [x] + Sin [3 x] == 0, x]
We see that it is not possible to obtain exact solutions, so we try to get them
approximate
In [2]: = NSolve [Sin [3 x] + Sin [x] == 0, x]
Solve::tdep:
The equations appear to involve transcendental
functions of the variables in an essentially
non-algebraic way.
NSolve [Sin [x] + Sin [3 x] == 0, x]
We have not achieved approximate solutions, so we try through subsidiaries conditions
In [3]: = cond = Sin [x] ^ 2 + Cos [x] ^ 2 == 1
2 2
COS [x] + Sin [x] == 1
In [4]: = Solve [{Sin [x] + Sin [3 x] == 0, cond}, {Sin [x], Cos [x]}]
2
{{Cos [x] - >-Sqrt [1 - Sin [3 x]],}}
{No [x] - >-without [3 x]},
2
{{Cos [x] - > Sqrt [1 - Sin [3 x]], Sin [x] - >-Sin [3 x]}}
We see that we are not successful.
Now we can only go to the iterative methods for obtaining approximate numerical
solutions.
First of all we need an initial value close to a solution to initiate convergence algorithm.
We found that initial value approx., from the ocular inspection of the intersection of the
graphs of the curves y = Sen(3x) e and = - Sin (x).
In [5]: = Plot [{[3 x], without-Sin [x]}, {x, - 2 Pi, 2Pi}]
We see that the graphs of the two curves intersect near x = 2, near x = 4, etc.
In[6]:= FindRoot[Sin[3 x]==-Sin[x],{x,2}]
{x -> 1.57096}
In[7]:= FindRoot[Sin[3 x]==-Sin[x],{x,4}]
{x - > 4.7122}
We also see that there are solutions for x between 2 and 4.
In[8]:= FindRoot[Sin[3 x]==-Sin[x],{x,{2,4}}]
{x - > 3.14159}
Exercise 4-8. Solve the following trigonometric equation:
x Sin [x] = 1/2
First of all represent the function xSen (x) - 1/2, to see, by simple Visual inspection, in
which approximate short origin points. These points will be taken as initial values for the
algorithms convergence
In[1]:= Plot[x Sin[x] -1/2, {x,0,10}]
We see that there is a solution near X = 1
In[2]:= FindRoot[x Sin[ x]-1/2==0,{x,1}]
{x - > 0.740841}
We also know that there are solutions for x between 1 and 10, and x between 5 and 10,
etc.
In[3]:= FindRoot[x Sin[ x]-1/2==0,{x,{1,10}}]
{x -> 2.97259}
In[4]:= FindRoot[x Sin[ x]-1/2==0,{x,{5,10}}]
{x - > - 15.6761}
Exercise 4-9. Solve the following exponential equation:
3
x 3 x
2 = 4 ( 2 )
As always, we try to get the initial values for the algorithm from graphical inspection
In [1]: = Plot [{2 ^(x^3), 4 2 ^(3 x)}, {x, - 4 2}]
We see a possible intersection of the two curves near the point x = - 1, so we take as the
initial value x =-1/2
In[2]:= FindRoot[2^(x^3)==4 2^(3 x), {x,-1/2}]
{x - > - 0.999569}
The solution obtained is very close to - 1, which leads us to suspect that x =-1 can be an
accurate solution. To check this, we apply the iterative algorithm with initial value x =-1
In[3]:= FindRoot[2^(x^3)==4 2^(3 x), {x,-1}]
{x - > - 1.}
And actually x =-1 is an exact solution of the equation.
To represent the above graph for x - 4-2, the possibility that to the right of x = 2 is
emerging may be more intersection points. To view it, we represent the graph between - 4
and 3.
In [4]: = Plot [{2 ^(x^3), 4 2 ^(3 x)}, {x, - 4, 3}]
Indeed, you see that there is another intersection near x = 2, by what we take x = 2 as
the initial value of the iterative algorithm.
In[5]:= FindRoot[2^(x^3)==4 2^(3 x), {x,2}]
{x - > 2.}
With that x = 2 is another exact solution of the equation.
Exercice 4-10. Resolve the following logarithmic equation:
3/2 3/2
x Log [x] = x Log [x ]
We started with graphical representation for the visual identification of the possible
initial value in the iterative algorithm
In[1]:= Plot[{(x Sqrt[x])Log[x], x Log[x Sqrt[x]]}, {x,0,3}]
We see that the two graphs intersect near x = 2, near x = 1 y near x = 0
In[1]:= FindRoot[(x Sqrt[x])Log[x]==x Log[x Sqrt[x]], {x,2}]
{x -> 2.25}
In[2]:= FindRoot[(x Sqrt[x])Log[x]==x Log[x Sqrt[x]], {x,0.5}]
{x - > 1.}
We have already obtained two exact solutions (x = 9/4 and x = 1). Lets try it now with
the possible solution near to x = 0
In[3]:= FindRoot[(x Sqrt[x])Log[x]==x Log[x Sqrt[x]], {x, 0.1}]
-10 -10
{x -> 1.01322 10 - 1.05729 10 I}
In[4]:= FindRoot[(x Sqrt[x])Log[x]==x Log[x Sqrt[x]], {x,{-0.1,0.1}}]
-9 -8
{x - > 2.07523 10 + 1.04477 10 I}
We see that the near-zero solutions are complex. The first has been found by the
Newton method and the second by the secant method.
4.4 SYSTEMS OF EQUATIONS
The command of Mathematica to solve systems are similar to the resolution of
equations. We have the following:
Solve [{equations}, {variables}]
solves the given system with variables also given and accurately.
Solve [{equations} & & Modulus == p, variable]
solves the specified system, for the specified variables, but module p.
Reduces [{equations}, {variables}]
simplifies everything system and considers its solutions, both in terms of the
given variable, and in terms of possible parameters included in the
equations. It also offers solutions with logical links between ellas.
Solve [{equations}, {variables1}, {variables2}]
Solve the system for the variablesw of the first group, eliminated in the
second group.
Eliminate [{equations}, {variables}]
fix the system, removed the explicit variables.
In[3]:= N[%]
2 2 4 2 2 2 2 2 2
b p (4 a - 4 a b - 4 a r + 4 b r ) ==
4 4 2 2 4
a (b - 2 b r + r )
In[4]:= Solve[sistema1, x, y]
{{x -> 1 + 2 a}}
In[5]:= Solve[sistema1, x, a]
-9 + y
{{x -> }}
2
In[6]:= Eliminate[sistema1, a]
y == 9 + 2 x
In[7]:= Eliminate[sistema1, x]
11 y
a == -() + -
4 4
Exercise 4-14. Solve the system formed by the equations:
x
COS []
Pi 5 3/2
- = y, -(-) + y = Sen[x ]
2 4
x/16
E
First of all we try to an exact solution
In[1]:=Solve[{E^(-(x/4)^2) Cos[x/Pi]==y, y-5/4==Sin[x^(3/2)]}, {x, y}]
Solve::tdep:
The equations appear to involve transcendental
functions of the variables in an essentially
non-algebraic way.
x
Cos[]
Pi 5 3/2
Solve[{- == y, -(-) + y == Sin[x ]}, {x, y}]
2 4
x /16
E
By simple inspection it is seen that there are two solutions. The first is near the point
(2.5, 0.5) and the second to the point (3, 0.3)
In[6]:= FindRoot[{E^(-(x/4)^2) Cos[x/Pi] == y, y-5/4 == Sin[x^(3/2)]},
{x,2.5},{y,0.5}]
{x -> 2.54105, y -> 0.461103}
In[7]:= FindRoot[{E^(-(x/4)^2) Cos[x/Pi] == y, y-5/4 == Sin[x^(3/2)]},
{x,3},{y,0.3}]
{x -> 2.9746, y -> 0.336065}
We already have two approximate solutions of the system.
4.5 SYSTEMS OF LINEAR EQUATIONS
Systems of linear equations can be converted to array form and solve them using the
calculation with matrices. A system can be written in the form M. X = B, where X is the
vector of variables, B the vector of independent terms and M the matrix of coefficients of
the system. If M is a square matrix and the determinant of the matrix M is non-null, M is
invertible, and the unique solution of the system can be written as X = M-1 B. In this case
the function Linearsolve offers the solution.
If the determinant of M is zero, the system has infinite solutions, with which there are rows
or columns in M that are linearly dependent. In this case is calculated the number of
redundant equations (function RowReduce), to find out how many variables have to be set to
infinite solutions.
If the matrix M is rectangular (not square), may be the system undetermined (number of
equations < number of variables), overdetermined (number of ecuacionres greater than the
number of variables) or non-singular (number of equations = number of variables and M non-
zero determinant).
An indeterminate system can ter infinite solutions, or none, and the same thing happens
to an overdetermined system. If there is no solution for a system, it is called inconsistent
(incompatible), and if there is at least one solution, called consistent (compatible).
The system M. X = B is called homogeneous when the vector B is the null vector. The
system will be of the form M. X = 0. If the determinant of M is non-null, the unique
solution of the system is the null vector (obtained with LinearSolve function). If the
determinant of M is zero, the system has infinite solutions (compatible is indeterminate).
Solutions will be using NullSpace.
Subsequently to consider the Rouche-Froebenius theorem, all these concepts on how to
and the different kinds of solutions of systems of linear equations will be organized.
Mathematica provides functions specific to solve systems of linear equations whose
syntax is as follows:
LinearSolve [B M] gives the vector X that solves the M System. X = B
NullSpace [M] gives a set of vectors, whose linear combinations are the solutions
of the homogeneous system M. X = 0 (Det [M] = 0)
RowReduce [M] transforms the matrix M in another array which has no rows or
redundant columns (gives M range).
When the Solve function offers the solution of a linear system, this coincides with the
solution offered by LinearSolve.
When LinearSolve applies to a linear system with infinite solutions, it offers only one
of ellas.
In[1]:= M={{1,5},{2,1}}
{{1, 5}, {2, 1}}
In[2]:=LinearSolve[M,{3,5}]
22 1
{, -}
9 9
You can also find solution in matrix form as follows:
In [3]: = Inverse [M]. {3,5}
22 1
{, -}
9 9
LinearSolve also solves systems based on parameters. If we want to solve the system of
equations x + 5y = a, 2 x + y = b, we have
In[4]:= LinearSolve[M,{a,b}]
5 (2a - b) 2a - b
{a - , -}
9 9
LinearSolve also gives the solution of a homogeneous system with non-zero
determinant of the matrix of coefficients. If we want to solve the system of equations x +
5y = 0 2 x + y = 0, we have
In [5]: = LinearSolve [M, {0,0}]
{0, 0}
Now considered the system 3 x + 4y = 1, 3 x + 4y = 2
In[6]:=M1={{3,4},{3,4}}
{{3, 4}, {3, 4}}
In[7]:=Det[M1]
0
In[8]:= LinearSolve[M1,{1,2}]
LinearSolve::nosol:
Linear equation encountered which has no solution.
We see that when the system has no solution, implies Mathematica.
The following is an example of a system with infinite solutions (x+3y + 4z = 1, 2 x +
3y + 3z = 1). In this case, Mathematica offers one of them (the more trivial)
In[9]:=M2={{1,3,4},{2,1,3}}
{{1, 3, 4}, {2, 1, 3}}
In[10]:= LinearSolve[M2,{1,1}]
2 1
{-, -, 0}
5 5
4.6 ROUCHE -FROBENIUS THEOREM
Rouche-Frobenius theorem allows the analysis of the solutions of a linear system of
ecuations and the calculation of these solutions. A system of m equations with n unknowns
has any solution if and only if the rank of the matrix of coefficients coincides with the
rank of the array extended with the vector column of the system-independent terms. If the
two ranges are equal and equal to the number of unknowns, the system has a unique
solution. If the two ranges are the same but lower than the number of unknowns system
has infinite solutions. If they are different the system has no solution.
Let A the matrix of coefficients of the system and (B) the vector of independent terms.
If range(A)range(B), the system is inconsistent (no solution). If range(A) = range (B) < n,
the system is indefinite (has infinite solutions). If (A) range = range (B) = n, the system
has unique solution. Practical exercises of application of Rouche-Frobenius theorem is
presented below.
Exercise 4-15. Study and solve the system:
2 x 1 + x 2 + x 3 + x 4 = 1
x 1 + 2 x 2 + x 3 + x 4 = 1
x 1 + x 2 + 2 x 3 + x 4 = 1
x 1 + x 2 + x 3 + 2 x 4 = 1
In[1]:= A={{2,1,1,1},{1,2,1,1},{1,1,2,1},{1,1,1,2}};
In[2]:= RowReduce[A]
{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}
In[3]:= B={{2,1,1,1,1},{1,2,1,1,1},{1,1,2,1,1},{1,1,1,2,1}};
In[4]:= RowReduce[B]
1 1 1
{{1, 0, 0, 0,-}, {0, 1, 0, 0,-}, {0, 0, 1, 0,-},}
5 5 5
1
{{0, 0, 0, 1,-}}
5
We see that the matrices A and B (expanded), have range 4, which also coincides with
the number of unknowns. Then the system has unique solution (compatible determined).
LinearSolve function is used to callcular your solution
In [5]: = LinearSolve [, {1,1,1,1}]
1 1 1 1
{-, -, -}
5 5 5 5
Exercise 4-16. Study and solve the system:
x 1 - x 2 + x 3 = 1
4 x 1 + 5 x 2 - 5 x 3 = 4
2 x 1 + x 2 - x 3 = 2
x 1 + 2 x2 - 2 x 3 = 1
In[1]:= A1={{1,-1,1},{4,5,-5},{2,1,-1},{1,2,-2}};
In[2]:= RowReduce[A1]
{{1, 0, 0}, {0, 1, -1}, {0, 0, 0}, {0, 0, 0}}
In[3]:= B1={{1,-1,1,1},{4,5,-5,4},{2,1,-1,2},{1,2,-2,1}};
In[4]:= RowReduce[B1]
{{1, 0, 0, 1}, {0, 1, - 1, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}
We see that the range of A1 and B1 match and its value is 2, which is less than the
number of unknowns from the system (3). The system will therefore have infinite
solutions (compatible unknown). If we try to resolve it with the function LinearSolve, we
will only obtain a (the more trivial) solution
In [5]: = LinearSolve [A1, {1,4,2,1}]
{1, 0, 0}
As the range of A1 is 2, to obtain the infinite solutions, we consider any minor of order
2 with nonzero determinant. For example:
In [6]:=Det{{1,-1},{4,5}}
9
Now, we solve the system formed by the two equations whose coefficients are included
in the determining factor considered in the previous step. Only 2 variables are taken into
account and the rest (one) are considered as parameters
In[7]:= LinearSolve[{{1,-1},{4,5}},{1-a,4+6 a}]//Expand
a 10 a
{1 + -, -}
9 9
a 10a
{1 +-,, a } when the parameter to vary in real numbers.
9 9
Note that the trivial solution {1,0,0} initially offered LinearSolve is a special case of the
general solution (a = 0).
Exercise 4-17. Study and solve the system:
x + 2 y + 3 z = 6
x + 3 y + 8 z = 19
2 x + 3 y + z = - 1
5 x + 6 y + 4 z = 5
In[1]:= A2={{1,2,3},{1,3,8},{2,3,1},{5,6,4}};
In[2]:= RowReduce[A2]
{{1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {0, 0, 0}}
In[3]:= B2={{1,2,3,6},{1,3,8,19},{2,3,1,-1},{5,6,4,5}};
In[4]:= RowReduce[B2]
{{1, 0, 0, 1}, {0, 1, 0, - 2}, {0, 0, 1, 3}, {0, 0, 0, 0}}
We see that the range of A2 and B2 coincide and its value is 3, which is equal to the
number of unknowns from the system (3). The system will therefore have a unique
solution (compatible determined). The only solution is obtained with the function
LinearSolve.
In [5]: = LinearSolve [A2, {6.19, 5, - 1}]
{1, - 2, 3}
Exercise 4-18. Study and solve the system:
x + 2 y + 3 z + t = 6
x + 3 y + 8 z + t = 19
In[1]:=A3={{1,2,3,1},{1,3,8,1}};
B3={{1,2,3,1,6},{1,3,8,1,19}};
In[2]:= RowReduce[A3]
{{1, 0, - 7, 1}, {0, 1, 5, 0}}
In [3]: = RowReduce [B3]
{{1, 0, - 7 1, - 20}, {0, 1, 5, 0, 13}}
We see that the range of A3 and B3 match and its value is 2, which is less than the
number of unknowns from the system (4). The system will therefore have infinite
solutions (compatible unknown). If we try to resolve it with the function LinearSolve, we
will only obtain a (the more trivial) solution
LinearSolve {6.19} [A3]
{- 20, 13, 0, 0}
As the A3 range is 2, to obtain the infinite solutions, we consider any minor of order 2
with nonzero determinant. For example:
In [6]:=Det{{1,2},{1,3}}
1
We now meet the system formed by the two equations whose coefficients are included
in the considered determinant in the previous step (which in this example are obviously
the two equations of the system). Only takes into account two variables involved in the
determinant (x e and), and other (z and t) are considered as parameters.
In[4]:= LinearSolve[{{1,2},{1,3}},{6-3a-b,19-8a-b}]//Expand
{- 20 + 7 a - b, 13 - 5}
Then the infinite solutions will be:
{- 20 + 7 a - b, 13 - 5 a, a, b} when the parameters a and b vary in real numbers.
Note that the trivial solution {-20,13,0,0} that it initially offered LinearSolve is a
special case of the general solution (a = 0, b = 0).
Exercise 4-19. Study and solve the system:
x 1 + 2 x 2 - x 3 = 10
2 x 1 + 4 x 2 - 2 x 3 = 5
x 1 + x 2 + x 3 = 6
In[1]:= A4={{1,2,-1},{2,4,-2},{1,1,1}};
B4={{1,2,-1,10},{2,4,-2,5},{1,1,1,6}};
In[2]:= RowReduce[A4]
{{1, 0, 3}, {0, 1, - 2}, {0, 0, 0}}
In [3]: = RowReduce [B4]
{{1, 0, 3, 0}, {0, 1, - 2, 0}, {0, 0, 0, 1}}
The A4 range is 2 and the B4 is 3, therefore the system has no solution (incompatible).
If we try to apply the function LinearSolve, the own Mathematica tells us that the system
has no solutions.
In[4]:= LinearSolve[A4,{10,5,6}]
LinearSolve::nosol:
Linear equation encountered which has no solution.
LinearSolve [{{1, 2, - 1}, {2, 4, - 2}, {1, 1, 1}}, {10, 5, 6}]
4.7 HOMOGENEOUS SYSTEMS
The system A. X = B is homogeneous if the vector of independent terms B is null, so
all homogeneous system will be the way: A. X = 0. In a homogeneous system, the rank of
the matrix of coefficients and the rank of the array extended with independent terms
column always coincide. If we apply the Rouche-Frobenius theorem, a homogeneous
system will have a unique solution when the determinant of the matrix A is non-zero. This
unique solution is the null vector, since the null solution always homogeneous systems
have it. A homogeneous system will have infinite solutions when the determinant of the
matrix A is zero. In this case the infinite solutions are calculated as in general systems, or
also using NullSpace [A] function. LinearSolve function only gives the null solution to the
homogeneous systems in Mathematica.
Exercise 4-20. Study and solve the system:
x 1 + 2 x 2 - x 3 = 0
2 x 1 - x 2 + x 3 = 0
3 x 1 + x 2 = 0
In [1]: = A5 = {{1,2, - 1}, {2, - 1, 1}, {3,1,0}};
In [2]: = Det [A5]
0
The system is homogeneous and the determinant of the matrix of coefficients is null,
which will have infinite solutions. We note that function LinearSolve offers only the trivial
solution.
In[3]:= LinearSolve[A5,{0,0,0}]
{0, 0, 0}
In[4]:= RowReduce[A5]
1 3
{{1, 0, -}, {0, 1, -(-)}, {0, 0, 0}}
5 5
As the A5 range is 2, to obtain the infinite solutions, we consider any minor of order 2
with nonzero determinant. For example:
In [5]:=Det{{1,2},{2,-1}}
-5
Now, we solve the system formed by the two equations whose coefficients are included
in the determining factor considered in the previous step. Only takes into account two
variables involved in the determining factor (x 1 and x 2), and the rest (3 x) is considered
as a parameter
In[6]:= LinearSolve[{{1,2},{2,-1}},{a,-a}]//Expand
-a 3 a
{, }
5 5
Then the infinite solutions will be:
-3 a
{, , a} when to vary in the real numbers.
5 5
If we multiply by 5 previous vector we have a simple expression of the general solution
of the homogeneous system
{-a, 3a, 5a} when to vary in the real numbers.
If we apply the function NullSpace we obtain a basis of the kernel of the matrix of
the system, i.e., a base of the set of solutions of the system A. X = 0, which is precisely the
homogeneous system that we want to solve
In [7]: = NullSpace [A5]
{{- 1, 3, 5}}
The set of solutions will be the linear combinations of the basis elements. But as in this
case the base is formed by a single vector, the general solution will be a generic constant
for the vector product, so the result matches found by the general method
{-a, 3a, 5a} when to vary in the real numbers.
Exercise 4-21. Study and solve the system:
3 x 1 + x 2 + x 3 - x 4 = 0
2 x 1 + x 2 - x 3 + x4 = 0
x 1 + 2 x 2 + 4 x 3 + 2 x 4 = 0
2 x 1 + x 2 - 2 x 3 - x 4 = 0
In [1]: = A6 = {{3,1,1,-1}, {2.1, - 1, 1}, {1,2,4,2}, {2.1, - 2, - 1}};
In [2]: = Det [A6]
-30
As the determinant of the coefficient matrix is non-zero, the system has only the trivial
solution. If we try to find a basis of the space of solutions, we can see that you there
In[3]:= NullSpace[A6]
{}
In[4]:= LinearSolve[A6,{0,0,0,0}]
{0, 0, 0, 0}
Exercise 4-22. Study and solve the system:
2 x 1 + x 2 - x 3 + 3 x 4 = 0
5 x 1 + x 2 + x 3 + 11 x 4 = 0
x 1 + 2 x 2 - 4 x 3 - 2 x 4 = 0
x 1 - x 2 - 3 x 3 - 5 x 4 = 0
In [1]: = H = {{2.1, - 1, 3}, {5,1,1,11}, {1,2, - 4, - 2}, {1, - 1, 3, 5}};
In [2]: = Det [H]
0
As the determinant is zero, the system has infinite solutions. To find them, we calculate
a basis of the kernel of H, which coincides with a basis of the space of solutions of the
homogeneous system
In [3]: = NullSpace [H]
{{- 8, 7, 0, 3}, {- 2, 7, 3, 0}}
Solutions will be combinations of elements of the base, then they will be written as:
{{- 8, 7, 0, 3} + b. {- 2, 7, 3, 0}} = {-8a-2b, 7a + 7b, 3b, 3a}
When the parameters a and b are real numbers.
Exercise 4-23. Study and resolve, according to the values of m, the system:
m x + y + z = 1
x + m y + z = m
x + y + m z = m ^ 2
In [1]: = [m_] A7 = {{m, 1, 1}, {1, 1}, {1,1,m}}
{{m, 1, 1}, {1, 1}, {1, 1, m}}
We consider the matrix of coefficients of the system as a function of m, in order to
study their rank according to the values of m
In[2]:= Solve[Det[A7[m]]==0,m]
{{m - > - 2}, {m - 1}, {m - 1}}
The values of m which determine the rank of the array are - 2 and 1.
In [3]: = B7 [m_] = {{m, 1, 1, 1}, {1, m, 1, m}, {1,1,m,m^2}}
2
{{m, 1, 1, 1}, {1, m, 1, m}, {1, 1, m, m}}
We are going to study the case m = - 2
In[4]:= RowReduce[A7[-2]]
{{1, 0, -1}, {0, 1, -1}, {0, 0, 0}}
In[5]:= RowReduce[B7[-2]]
{{1, 0, - 1, 0}, {0, 1, - 1, 0}, {0, 0, 0, 1}}
We see that the range of the two arrays is different, with which the system is
inconsistent (no solution) for m =-2
Now study the case m = 1
In[6]:= RowReduce[A7[1]]
{{1, 1, 1}, {0, 0, 0}, {0, 0, 0}}
In[7]:= RowReduce[B7[1]]
{{1, 1, 1, 1}, {0, 0, 0, 0}, {0, 0, 0, 0}}
Now the range of the two matrices is 1, which is less than the number of unknowns.
Then the system has infinite solutions (compatible unknown).
As the range of A7 [1] is 1, for infinite solutions, we consider any minor of order 1 with
nonzero determinant (any coefficient of the system, for example a 1 in the first equation
coefficient).
Now, we solve the system formed by the equation whose coefficients contain to be
considered minor (which in this example is obviously the first equation of the system).
Only take into account the variable x 1, and the rest (x 2 and x 3) are considered as
parameters.
In[8]:= LinearSolve[{{1}},{1-a-b}]
{1 - a - b}
Then the infinite solutions will be:
{1 - a - b, a, b} when a and b are real numbers.
If we solve the system with LinearSolve, we get the trivial solution (a = 0, b = 0)
In [9]: = LinearSolve [A7 [1], {1,1,1}]
{1, 0, 0}
If we consider the case where m is different - 2 and - 1, the system has a solution, that
we are given by the function LinearSolve
In[10]:= LinearSolve[A7[m],{1,m,m^2}]//Expand
2 3
m m 1
{m + - - -
1 - m 1 - m 3
2 - 3 m + m
2
m 2 m
- + +
3 3
(1 - m) (2 - 3 m + m ) 2 - 3 m + m
2 3
m 2 m
- + - -
3 3
(1 - m) (2 - 3 m + m ) (1 - m) (2 - 3 m + m )
4 4
m 2 m
- - -
3 3
2 - 3 m + m (1 - m) (2 - 3 m + m )
5 6
m m
- + -,
3 3
(1 - m) (2 - 3 m + m ) (1 - m) (2 - 3 m + m )
2
m m 1
-() + + - -
1 - m 1 - m 3
(1 - m) (2 - 3 m + m )
2
m 2 m
- - - +
3 3
(1 - m) (2 - 3 m + m ) (1 - m) (2 - 3 m + m )
3 4
2 m m
- + - -
3 3
(1 - m) (2 - 3 m + m ) (1 - m) (2 - 3 m + m )
5
m
-,
3
(1 - m) (2 - 3 m + m )
2 4
1 2 m m
- + }
3 3 3
2 3 m + m 2-3 m + m 2-3 m + m
Exercise 4-24. Study and resolve, according to the values of m, the system:
m y = m
(1 + m) x - z = m
y + z = m
In [1]: = A8 [m_] = {{0, 0}, {m + 1, 0, - 1}, {0,1,1}}
{{0, 0}, {1 + m, 0, - 1}, {0, 1, 1}}
In[3]:= Solve[Det[A8[m]]==0,m]
{{m - > - 1}, {m - > 0}}
We can see that the values of m which determine the rank of the matrix of coefficients
of the system are m = 1 and m = 0
In[4]:= RowReduce[A8[-1]]
{{0, 1, 0}, {0, 0, 1}, {0, 0, 0}}
In[5]:= RowReduce[B8[-1]]
{{0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}
If m =-1, we see that the system has no solution incompatible because the rank of the
matrix of coefficients of the system is 2 and the augmented matrix is 3.
When m is zero the system is homogeneous, since independent terms are all null. To
make your study, we analyze the determinant of the matrix of coefficients of the system.
If m is not 0 and other than - 1, the system supports specific (unique solution), since the
ranges of the matrix of the system and of the augmented matrix coincide. The solution
using the LinearSolve function will be calculated.
-1 + m m
{ + , 1, -1 + m}
1 + m 1 + m
Exercise 4-25. Study and resolve, according to the values of m, the system:
3 x + 3 y - z = 0
-4 x - 2 y + m z = 0
3 x + 4 y + 6 z = 0
In[2]:= Solve[Det[A9[m]]==0,m]
46
{{m - >-}}
3
If m is different from 46/3, the system has only the trivial solution (no solution).
If m = 46/3, the system has infinite solutions, which will be given by the NullSpace
function
In [3]: = NullSpace [A9 [46/3]]
22
{{, -7, 1}}
3
Then the infinite solutions will be:
22
{a. {-, - 7 1}} = {22a/3, - 7a, to} when to runs the Royals.
3
5Chapter 5.
The Intersection function returns the elements common to all its arguments.
In [42]: Intersection = [{1, 4, 2, 3}, {6, 5, 4, 3}]
Out [42] = {3, 4}
The Union function returns a ranked list of all the different elements.
In [43]: = Union [{1, 4, 2, 3}, {6, 5, 4, 3}]
Out [43] = {1, 2, 3, 4, 5, 6}
Complement, Intersection and Join functions can take one or more arguments. The
Union, Intersection, and Complement eliminate duplicates.
In [44]: = Union [{1, 5, 3, 3, 2, 8, 4, 8, 5}]
Out [44] = {1, 2, 3, 4, 5, 8}
Note that Join together lists. The order is preserved and duplicates are not deleted.
In [45]: = Join [{1, 2, 3, 4}, {3, 4, 5, 6}]
Out [45] = {1, 2, 3, 4, 3, 4, 5, 6}
The functions Complement, Intersection and Union ordered elements of their arguments
when they calculate the result. As a result, all return ordered lists.
5.7 REORDERING LISTS
There are several functions to redistribute the terms of a list, such as reverse, Sort,
Rotateright, RotateLeft, Union, and Permutations. The general form of these functions is as
follows:
Reverse[list] reverses the order of elements in the list.
Sort[list] sorts the items of the list in the standard order.
RotateLeft[list, n] rotates the elements of the list n places to the left.
RotateRight[list, n]
rotates the elements of the list n places to the right.
RotateLeft[list] rotates the elements of the list 1 place to the left.
RotateRight[lista] rotates the elements in the list 1 place to the right.
Union[list] sorts the items of the list in the standard order,
eliminating the repeated.
Permutations[list]
gives a list with all the possible permutations of the input list.
Outer [list, list1, list2,]
gives the list of possible combinations of all the elements of the given
lists.
OrderedQ[list] gives True if items in the list are sorted.
Signature[list] gives the signature of the permutation needed to
transform the entry in the ordered list list in the standard order.
To display these possibilities of manipulation of lists, I build a list of random integers, I
call list.
In [17]: = list = Table [Random [Integer, {0, 15}], {10}]
Out [17] = {0, 1, 9, 14, 7, 5, 14, 14, 7, 8}
The Sort function sorts the items in order Canon, by placing the numbers in increasing
order. Union also sorts the elements, in addition to eliminate duplicates
In [18]: = Sort [list]
Out [18]: = {0, 3, 5, 7, 7, 8, 9, 14, 14, 14}
In [18]: = Union [list]
Out [18]: = {0, 3, 5, 7, 8, 9, 14}
Reverse, function reverses the order of the items in the list
In [19]: = reverse [list]
Out [19] = {8, 7, 14, 14.5, 7, 14, 9, 3, 0}
Mathematica provides two functions to rotate lists: TotateLeft and RotateRigth. With
these functions, a list can be rotated so that a given item is at the top of the list. Here I made
a rotation from the list in such a way that the first three elements pass at the end of the list
In [20]: = RotateLeft [%, 3]
Out [20] = {14, 5, 7, 14, 9.3, 0, 8, 7, 14}
Here I made a rotation from the list in such a way that the last four elements pass from
the end at the beginning of the list
In [21]: = RotateRight [%, 4]
Out [21] = {0, 7, 14, 14, 5, 7, 8, 14, 9, 3}
A negative argument to RotateLeft is equivalent to RotateRight with the absolute value
of the argument.
The Permutations function, gives the list of all the permutations of a list.
In [22]: = Permutations [{a, b, c}]
Out [22] = {{a, b, c}, {a, c, b}, {b, c},}
{{b, c, a}, {c, a, b}, {c, b, a}}
In [23]: = Outer [List, {a, b}, {c, d}]
Out [23] = {{{a, c}, {a, d}}, {{b, c}, {b, d}}}
5.8 FUNCTIONS TO COUNT, CHANGE SHAPE, SELECT
AND SEARCH ITEMS FROM LISTS
Length (length) and Dimensions functions are used to determine the size of a list. Length
returns the number of elements, while Dimensions is intended for rectangular nested lists,
i.e. lists that contain sublists all the same length.
Flatten, FlattenAt, Partition and Transpose functions are to change the form of a list.
The Select function is designed to extract a list of values that meet a given criteria.
Position, Count, MemberQ and FreeQ functions selected, looking for and check the
status of items in lists.
Lets take the general form of these functions.
Length[List] gives the number of items in the list.
Dimensions[list] gives the dimensions of the array represented by
the list.
Flatten [list] gives a single flat list without levels.
Flatten [list, n] gives a single flat list with n levels.
FlattenAt [list, i] flattens the sublist that appears in position i.
FlattenAt [list, {i, j,}]
Flattens the sublists that appear in the positions i, j,
Partition [list {n1, n2,}, {d1, d2,}]
Partitions the list into groups or elements, with levels of displacement
of di.
Traspose [list] gives a list traspuesta.
Select [{e1, e2,, in}, criterion]
returns a list of the elements ei for which the criterion is true.
Position [list, f] gives the position when the shape is f within the list.
Count [lista, f] count gives the number of times it appears the form
f within the list.
MemberQ [list, f] check if the form f is on the list.
FreeQ [list, f] checks if the form f is not in the list.
Here are some examples
In [38]: = Length [{3, d, 4, t, to ^ 2}]
Out [38] = 5
2 by 5 array consists of a list of two lists, each of 5 elements. Note that Length tells us
that a list has thus two elements
In [39]: = Length [{{3, d, 4, t, to ^ 2}, {1, 2, 3, 4, 5}}]
Out [39] = 2
Dimensions gives us more detailed information about this matrix
In [40]: = Dimensions [{{3, d, 4, t, to ^ 2}, {1, 2, 3, 4, 5}}]
Out [40] = {2.5}
In [46]: = vector = Range [8]
Out [46] = {1, 2, 3, 4, 5, 6, 7, 8}
Then, with Partition, I believe a partition of the vector into two parts to form a matrix
with two rows and four columns, which I call matrix
In [47]: = array = Partition [vector, 4]
Out [47] = {{1, 2, 3, 4}, {5, 6, 7, 8}}
Vector partitioning can be visualized as an array
In [48]: = MatrixForm [Matrix]
Out [48] = 1 2 3 4
5 6 7 8
Make partitions can be very useful when working with data that have some structure. For
example, if you have data that represents points in three dimensional space, it can be
convenient to split the data into groups of three
In [49]: = Partition [{1, 34, 456, 2, 33, 453, 3, 36, 435}, 3]
Out [49] = {{1, 34, 456}, {2, 33, 453}, {3, 36, 435}}
The third argument of Partition specifies an offset. Here I am three lists with a
displacement of one
In [50]: = Partition [{a, b, c, e, f, g}, 3, 1]
Out [50] = {{a, b, c}, {b, c, d}, {c, d, e}, {d, e, f}, {e, f, g}}
Flatten (Flattening, smoothing) eliminates nested lists. Returns a single list, flat, no levels
In [52]: = Flatten [Matrix]
Out [52] = {1, 2, 3, 4, 5, 6, 7, 8}
In [4]: = {{{3, 6}, {6, 9}}, {{6, 9}, {9, 12}}}
In [5]: = Flatten [t]
Out [5] = {3, 6, 6, 9, 6, 9, 9, 12}
In [6]: = Flatten [t, 1]
Out [6] = {{3, 6}, {6, 9}, {6, 9}, {9, 12}}
In [7]: = FlattenAt [{{a, b}, {c, d}}, 2]
Out [7] = {{a, b}, c, d}
Thus, Partition builds an array from a vector or list, and Flatten returns a vector or list
from an array.
The Transpose function, transposing a matrix, turning rows into columns and columns in
rows
In [53]: Transpose = [{{a, b, c}, {d, e, f}}]
Out [53] = {{a, d}, {b, e}, {f, c}}
In [63]: = Select [{2, 7, a, 5, 4.5 - 3 - 5} {, Positive}]
Out [63] = {2, 4.5, 5, 7}
In [1]: = Position [{a, b, c, a, b}, to]
Out [1] = [{1}, {4}]
In [1]: = Count [{a, b, c, a, b}, to]
Out [1] = 2
In [1]: = MemberQ [{a, b, c}, d]
Out [1] = False
In [1]: = MemberQ [{a, b, c}, to]
Out [1] = True
5.9 APPLYING FUNCTIONS TO LISTS
Apply, Map, NextList, Fold, FoldList, ComposeList and Scan functions allow you to
apply functions to lists. Lets take the general form of these functions
Apply [f], {a, b,}, applies f to the list, resulting in f [a, b,]
Apply [f, expression, n] applies f to the expression level n.
Apply [f, expression] or f @ expression
applies f to the expression.
Map [f], {a, b,}, applies f to each element of the list,
resulting in {f [a], f [b],]}
Map [f, expression] or f / @ expression
applies f to the first level of the expression
components.
MapAll [f, expression] or f / / @ expression
applies f to all levels of components of the
expression.
Map [f, expression, n] applies f to each part of the expression to
the level n.
MapAt [f, expression, {part1, part2,}]
applies f to specified parts of the expression.
MapIndexed[f, expression]
applies f to all components of the expression giving the index of
status of each item in the list as the second argument of f.
MapIndexed[f, expression, n]
applies f to each part of the expression to n-tier, giving the
location of each element of the list or second rate f argument.
MapThread [f, {expression1, Expression2,}]
applies f to the corresponding elements in each expressioni.
MapThread [f, {expression1, Expression2,}, n]
applies f to the corresponding elements in each expressioni level
n.
NestList [f, x, n] generates the list {x, f[x], f[f[x]]} n times.
FoldList [f, x, {a, b,}] generates the list {x, f [x, a], f [f [x, a], b]}.
Fold [f, x, {a, b,}] gets the last element of FoldList.
ComposeList [{f1, f2,}, x]
generates the list {x, f1[x], f2[f1 [x]]}.
Scan[f, expression] evaluates f applied to each element of the
expression at a time.
Scan[f, expression, n] evaluates f applied to each element of the
expression by turn, to level n.
Here are some examples with these functions
In [1]: = Map [f, {a, b, c}]
Out [1] = {f [a], [b] f, f [c]}
In [2]: = f / @ {a, b, c}
Out [2] = {f [a], [b] f, f [c]}
In [3]: = Apply [f, {a, b, c}]
Out [3] = f [a, b, c]
In [4]: = f @ {a, b, c}
Out [4] = f [a, b, c]
In [5]: = f [{2, 4, 5, 3}]
Out [5] = f [{2, 4, 5, 3}]
In [6]: = Map [f, {2, 4, 5, 3}]
Out [6] = {f [2], f [4], f [5], f [3]}
In [7]: = Map [f, a + b x]
Out [7] = f [a] + f [x-b]
In [8]: = Apply [Plus, {a, b, c}]
Out [2] = a + b + c
In [8]: = mean [list_]: = Apply [Plus, list] / Length [list]
In [9]: = Apply [List, a + b + c]
Out [9] = {a, b, c}
In [10]: = m = {{a, b, c}, {b, c, d}}
Out [10] = {{a, b, c}, {b, c, d}}
In [11]: = Apply [f, m]
Out [11]: = f [{s, b, c}, {b, c, d}}]
In [12]: = Apply [f, m, {1}]
{Out [12] = {f [a, b, c}, f [b, c, d]}
In [1]: = Apply [f, m, {0,1}]
Out [1] = f [f [a, b, c], f [b, c, d]}]
In [2]: = take2 [list_]: = Take [list, 2]
In [3]: = Map [take2, {{1, 3, 4}, {5, 6, 7}, {2, 1, 6, 6}}]
Out [3] = {{1, 3}, {5, 6}, {2.1}}
In [4]: = Map [f, a + b + c]
Out [4] = f [a] + [b] f + f [c]
In [5]: = Map [Sqrt, g [x ^ 2, x ^ 3]]
Out [5] = g [Sqrt [x ^ 2], Sqrt [x ^ 3]]
In [6]: = m = {{a, b}, {c, d}}
Out [6]: = {{a, b}, {c, d}}
In [7]: = Map [f, m]
Out [7] = {f [{a, b}], f [{c, d}]}
In [8]: = MapAll [f, m]
Out [8] = f [{f [{f [a], f [b]}], f [{f [c], f [d]}]}]
In [9]: = Map [f, m, {2}]
Out [9] = {{f [a], f [b]}, {f [c], f [d]}}
In [11]: = mm = {{a, b, c}, {b, c, d}}
Out [11] = {{a, b, c}, {b, c, d}}
In [12]: = MapAt [f, mm, {{1,2}, {2, 3}}]
Out [12] = {{a, [b] f, c}, {b, c, f [d]}}
In [13]: = Position [mm, b]
Out [13] = {{1, 2}, {2, 1}}
In [14]: = MapAt [f, mm, %]
Out [14] = {{a, [b] f, c}, {f [b], c, d}}
In [15]: = MapAt [f, {a, b, c, d}, {{2}, {3}}]
Out [15] = {a, f [b], f [c], d}
In [16]: = t = 1 + (3 + x) ^ 2 / x
(3 + x) ^ 2
Out [16] = 1 +-
x
In [17]: = FullForm [t]
Out [17] //FullForm= Plus [1, Times [Power [x, - 1], Power [Plus [3 x], 2]]]
In [18]: = MapAt [f, t, {{2, 1, 1}, {2, 2}}]
f [(3 + x) ^ 2]
Out[18]= 1 + -
f [x]
In [19]: = MapIndexed [f, {a, b, c}]
Out [19] = {f [a, {1}], f [b, {2}], f [c, {3}]}
In [20]: = MapIndexed [f, {{a, b}, {c, d}}, 2]
Out [20] = {f [{f [a, {1, 1}], f [b, {1, 2}]}, {1}],}
{f [{f [c, {2, 1}], f [d, {2, 2}]}, {2}]}
In [21]: = MapThread [f, {{a, b, c}, {ap, bp, cp}}]
Out [21] = {f [a, ap], f [b, bp], f [c, cp]}
In [22]: = Mapthread [f, {{a, b}, {ap, bp}, {app, bpp}}]
Out [22] = {f [a, ap, app], f [b, bp, bpp]}
In [23]: = Map [f, {a, b, c}]
Out [23] = {f [a], [b] f, f [c]}
In [24]: = FoldList [f, x, {a, b, c}]
Out [24] = {x, f [x, a], f [f [x, a], b], f [f [f [x, to], b], c]}
In [25]: = Fold [f, x, {a, b, c}]
Out [25] = f [f [f [x, a], b], c]
In [26]: = FoldList [Plus, 0, {a, b, c}]
Out [26] = {0, a, a + b, a + b + c}
In [27]: = Scan [Print, {a, b, c}]
to
b
c
In [28]: = Scan [Print, 1 + x ^ 2, Infinity]
1
x
2
x ^ 2
5.10 MATHEMATICALS OPERATIONS WITH LISTS
Lists allow to apply mathematical functions. But only those functions that have the
attribute Listable can be applied. If you want to apply to a list a function that does not
have the attribute Listable, it is necessary to provide it with the previously (in the previous
chapter are applied all matter concerning attributes of functions).
Suppose we have some data you want to add. We can indicate to Mathematica to add
them by Sum (which has the attribute Listable)
In [67]: = Sum [i ^ 2, {, 5}]
Out [67] = 55
We then see examples of application functions with the attribute Listable lists
In [75]: = Log [{2, 4, 5, 3}]
Out [75] = {Log [2], Log [4], Log [5], Log [3]}
In [77]: = [{2, 4, 5, 3}]
Out [77] = {[2], not [4], [5] without [3]}
In [78]: = {1, 2, 3} + {a, b, c}
Out [78] = {1 + to 2 + b, 3 + c}
In [2]: = {3, 5, 1} ^ 2 + 1
Out [2] = {10, 26, 2}
In [6]: = v = {2, 4, 3.1}
Out [6] = {2, 4, 3.1}
In [7]: = v / (v - 1)
Out [7] = {2, 4/3, 1.47619}
In [3]: = {6, 7, 8} - {3.5, 4, 2.5}
Out [3] = {2.5, 3, 5.5}
Exercise 5-1. Generate a list of 16 random integers between 0 and 100, and
extract from it the whole exceeding 50.
In [1]: = [list] Clear
In [2]: = list = Table {Random [Integer, {0, 100}], {i, 16}}
Out [2] = {76, 21, 49, 27, 13, 42, 21, 54, 16, 1, 68, 41, 51, 83, 79, 37}
We now define a function then for usra the Select function:
In [3]: = f [x_]: = x > 50
In [4]: = Select [list, f]
Out [4] = {76, 54, 68, 51, 83, 79}
First, Im going to create the ordered list using the Range function
In [1]: = Range [1, 16, 2]
Out [1] = {1, 3, 5, 7, 9, 11, 13, 15}
Secondly, I am going to create the ordered list using the Table function
In [2]: = list = Table [2i-1, {i, 8}]
Out [2] = {1, 3, 5, 7, 9, 11, 13, 15}
Exercise 5-3. Calculate the number of permutations that can be built with the
elements of the set {a, b, c, d}. How would these permutations be built?
In [1]: = length [Permutations [{a, b, c, d}]]
Out [1] = 24
If we would like to explicitly construct the 24 permutations, we enable to Mathematica:
In [2]: = Permutations [{a, b, c, d}]
In [1]: = Map [Min, Transpose [{{15, 17, 18, 32, 29}, {14, 18, 22, 29, 26}}]]
Out [1] = {14, 17, 18, 29, 26}
5.11 RULES
In general, a rule is a method to replace an object, symbol or variable with a value
in any expression. For example, when we find the limit of a function f [x_] when the
variable tends to a value x 0, we are applying the rule x - > x 0 to the function f.
When you apply a rule to an expression commonly used notation /. between
the expression and the value of the symbol, variable or object. Thus, in the above
example write: f [x_] /. x - > x 0.
From this definition already be sense possible immediate applications of the rules, such
as the calculation of values of functions in certain points, the calculation of the true value of
rational expressions, the calculation of limits, simplifying trigonometric expressions, etc.
Graphics, such as Plot or ContourPlot orders options, specified with rules.
In [52]: = Options [ContourPlot]
Out [52] = {AspectRatio - > 1, Axes - > False, AxesLabel - > None,}
AxesOrigin - > Automatic, AxesStyle - > Automatic,
Background - > Automatic,
ColorFunction - > Automatic,
ColorOutput - > Automatic, Compiled - > True,
ContourLines - True, Contours - > 10,
ContourShading - > True, ContourSmoothing - > None,
ContourStyle - > Automatic,
DefaultColor - > Automatic,
Epilog - > {}, Frame - > True, FrameLabel - > None,
T:System.Windows.Forms.FrameStyle - > Automatic, FrameTicks - > Automatic,
PlotLabel - > None, PlotPoints - > 15,
PlotRange - > Automatic, PlotRegion - > Automatic,
Prolog - > {}, RotateLabel - > True,
Ticks - > Automatic, DefaultFont: > $DefaultFont,
{DisplayFunction: > $DisplayFunction}
Among the functions that return rules, is Solve. The Solve function, tries to solve an
equation or system of equations specified in a list. When we can find solutions, Solve,
returns a list of lists of rules, or a nested list of rules.
For example, to solve a system of equations, the equations are specified within a list, and
the solution is returned as a list of two rules.
In [1]: = Solve [{2 x + 5y = 19, 3 x + 7y = 27}]
Out [1] = {{x - > 2-> 3}}
5.12 EQUALITY
Mathematica uses the symbol == to denote equality. Just as in the C
programming language, uses a double equal sign, ==, for comparisons and to specify
equations.
In [67]: Expand = [(x + y) ^ 2] == x ^ 2 + 2 x and + and ^ 2
Out [67] = True
NRoots function returns the solutions of an equation with the sign of equality and with
the logical And function between them. The solutions of the equation can be converted to
rules by using the ToRules function.
In [72]: = NRoots [x ^ 3 - 3 x ^ 2-17 x + 51 == 0, x]
Out [72] = x == - 4.12311 x == 4.12311
In [73]: = ToRules [%]
Out [73] = ({x - > - 4.12311}, {x - > 3.}, {x - > 4.12311})
In Mathematica, there are several functions to check equality and inequality,
among them are: == (Equals), = (SameQ),! = (Unequal) and =! = (UnsameQ).
The symbol == is an attempt to represent the mathematical equality. Mathematica returns
True if the left side is equal to the right side. If the quantities have different precision,
Mathematica checks if they are the same with the precision that has it lower.
In [74]: = N [Pi, 3] == N [Pi, 30]
Out [74] = True
The comparison is returned unevaluated when Mathematica cannot determine whether
the expressions are equal. The variable and could be equal to x if x e and refer to the same
value. As a result, Mathematica can not tell if this is true or false, so it returns it without
assessing.
In [75]: = x == and
Out [75] = x == and
The notation! = checks if the number on the left is different from the number on the right.
In [76]: = 1! = 2
Out [76] = True
On the other hand, = returns True if the expressions are syntactically identical (or equal
to the precision of the number that has less) and always returns False (false) otherwise.
In [77]: = N [Pi, 3] = N [Pi, 30]
Out [77] = True
In [78]: = N [Pi, 3] =! = N [Pi, 30]
Out [78] = False
In [79]: = x = and
Out [79] = False
In [80]: = x =! = and
Out [80] = True
5.13 IMMEDIATE RULES
We have already mentioned that another feature of the Mathematica package is the
possibility of making any expression substitutions or mathematical transformations based
on rules. The format in which indicated a rule and how it is applied to an expression, shown
in the following example:
In [39]: = x+Sin [x] - Cos [x] / x - > Pi
Out [39] = 1 + Pi
The above command indicates to the expression x + Sin (x) - cos (x) rule applies x - > Pi.
That rule in this case indicates a simple substitution of a variable with a value.
As well, this notation and thus apply rules, correspond to the concept of immediate rule.
In case of applying multiple rules to a same expression, these are indicated in a list, i.e.,
braces and separated by commas:
In [40]: = x ^ 2 * and ^ 3 + 2 x+3-x * and + 2. {x - > 2, and - > 1}
Out [40] = 11
The rules are simply a mechanism to replace a symbol with a value in an expression. The
operator /. (no space between / and.) or ReplaceAll (replace all) applies a rule immediate or
list of immediate rules, after evaluating the expression. Thus, the expression x + 5y. x - > 2
can be interpreted as x + 5y where x happens to be 2.
In [44]: = x + 5y. x - > 2
Out [44] = 2 + 5y
Using a list of rules, several substitutions can be made. Here we specify two immediate
rules of substitution in the same list.
In [45]: = x + 5y. {x - > 2, and - 3}
Out [45] = 17
The expression to the left of /. assessed before any replacement.
In [46]: = 2 x + 3 x. {2 x - > and 3 x - > 3}
Out [46] = 5 x
The left side is the first thing that is evaluated; 2 x + 3 x is replaced by 5 x. After none of
the two rules is already applicable to this result, because already there are 2 x and 3 x. That
is, that no rule is not invoked.
The rules also provide the ability to be applied recursively.
In the examples above the rules applied only once, but it may be desirable to apply an
immediate rule repeatedly to the same expression until this not change (until it is
completely simplified); This can be achieved by indicating, or rules, after the symbol / /.
instead of after /..
The difference between applying rules only once or repeatedly in a recursive manner, it
is given by the fact that, in the recursively rules applied repeatedly until you reach an
expression on which not can continue to apply them. Therefore, the rules, as well as serving
to make simple substitutions, on expressions, can be used to handle mathematical relations
upon them as, for example, in the following command, with which you want to apply two
known rules of the trigonometric functions to an expression:
In [43]: = Cos [x+y+Pi]-[x-and-Pi]
//. {Cos [a_ + b_]-> Cos [a] * [b] Cos - without [a] * [b],}
{No [a_ + b_]-> [a] without * Cos [b] + Cos [a] * [b]}
Out [43] =-(cos (x) cos (and)) + cos (and) sin (x) - cos (x) without (and) + sin (x) without
(and)
Repeatedly apply the rules governing the cosine and sine of the sum of two numbers,
until you reach an expression with trigonometric functions with simple arguments.
You can check that, after applying the above rules, to give the order to simplify, turns to
obtain as a result the original expression
In [44]: = Simplify [%]
Out [44] =-cos(x + y) + sin(x-y)
The simple conclusion is that the notation. an immediate rule applied repeatedly.
5.14 DEFERRED RULES
We have seen in the previous chapter about functions there are two types of assignments,
Set(=, inmediata), and SetDelayed(:=, diferida).
At the same time, Mathematica includes two types of rules, immediate (->) and
deferred rules (: >).
In the following example, x is replaced by the value returned by Random [] to specify the
rule. So, I get a list of identical values
In [47]: = Table [x, {5}]. x - > Random]
Out [47] = {0.853253, 0.853253, 0.853253, 0.853253, 0.853253}
The rules do not perform allocations. Despite that x - > 2 does Mathematica to replace x
by 2 in the expression, the value 2 is assigned to x. If you ask Mathematica on x, you will
see has no assigned value
In [48]: = x
Out [48] = x
Deferred rules are used when the expression of right: > should be evaluated to invoke the
rule. To use a deferred rule to replace x by Random [], I get a list of five different random
real numbers
In [49]: = Table [x, {5}]. x: > Random]
Out [49] = {0.772793, 0.866919, 0.330458, 0.251469, 0.427448}
In this case, if you ask Mathematica on x, is observed that already has assigned value
(which has been given to applying the deferred rule).
In [48]: = x
Out [48] = Random]
We see a table summary of used signs.
Notation Order Description
-
= Set immediate assignment
: = SetDelayed deferred allocation
-> Rule Immediate rule
:> RuleDelayed delayed rule
/. ReplaceAll to apply a rule or rule list
//. ReplaceRepeated
to enforce rules repeatedly
== Equal checks equality
! = Inequality checks unequal
= SameQ checks if they are syntactically equal
=! = UnsameQ checks if they are not equal.
In [63]: = root = Solve [x ^ 2 + 15 x + 42 == 0, x]
-15 + Srqt [75] - 15 - Sqrt [57]
Out[63] = {{ x -> }, {x -> }}
2 2
Two solutions have been obtained as a list of two rules.
Through the mechanism of substitution, you can verify the solution, replacing the values
obtained in the original equation
In [64]: = x ^ 2 + 15 x + 42 == 0. roots
2
15 (- 15 + Sqrt [57]) (- 15 + Sqrt [57])
Out[64]= {42 + - + - == 0,
2 4
2
15 (- 15 - Sqrt [57]) (- 15 - Sqrt [57])
42 + - + == 0}
2 4
To simplify the result, you can see that the roots satisfy the equation
In [65]: = Simplify [%]
Out [65] = {True, True}
Exercise 5-6. Use rules to simplify as much as possible the logarithm of a product
of four numbers.
If I use a rule that is applied only once, I have the following:
In [50]: = log [a b c d]. log [x_ y_] - > log [x] + log [and]
Out [50] = log [a] + [b c d] log
It is not a comprehensive simplification.
But if I use a rolling ruler, I have the following:
In [51]: = log [a b c d] / /. log [x_ y_] - > log [x] + log [and]
Out [51] = log [a] + [b] log + log [c] + log [d]
Representing a total simplification of the logarithm of a product.
Exercise 5-7. Find the value of the expression (x^3 + 2x^2-x-2) /(x^3+x^2-4x-4)
at the point x = 1
In [1]: = fraction = (x ^ 3 + 2 x ^ 2-x-2) /(x^3+x^2-4x-4)
In [2]: = fraction. x - > 1
Out [2] = 0
In [2]: = f [x_]: = x ^ 2
Exercise 5-10. Using patterns, finding simple functions that calculate the average
of a sequence of numbers and the elements of a list.
There are times that you want that a function can be applied to a single argument and
several arguments. How to write a function to calculate the average of a sequence of
numbers?. Here are rules for calculating the average of one, two or three elements.
In [1]: = media [a_]: = a
In [2]: = media [a_, b_]: = (a + b) / 2
In [3]: = media [a_, b_, c_]: = (a + b + c) / 3
Instead of writing rules for specific quantities of arguments, you can write a rule that
applies to one or more arguments by the patron__. The following definition calculates the
average of one or more quantities.
In [3]: = Clear [media]
In [4]: = media [x__]: = Plus [x] /Length [{x}]
In [5]: media = [a, b, c, d, e]
a + b + c + d + e
Out[5] = -
5
So far, the definition does not calculate the average of a list of numbers. After you have
added the following definition, the function will calculate the average of the elements in a
list.
In [6]: = media [{x__}]: = mid [x]
In [7]: average = [{1, 2, 3, 4, 5}]
Out [7] = 3
First we implement pattern that makes the integral of a sum is the sum of integrals
In [1]: = integrate [y_ + z_, x_]: = integrate [y, x] + integrate [z, x]
Thus we obtain the following progress:
In [2]: = integrate [x + b x ^ 2 + 3, x]
Out [2] = integrate [3 x] + integrate [x, x] + integrate [b x ^ 2, x]
Then we implement the pattern that makes the integral of a constant by a function the
product of constant by the integral of the function
In [3]: = [c_ x_, y_] integrate: integrate c = [y, x] /; FreeQ [c, x]
FreeQ [c, x] function indicates that it is true that c does not depend on the variable x (we
are saying to Mathematica that c is actually a constant, since initially Mathematica does not
know why it).
Thus we obtain the following progress:
In [4]: = integrate [x + b x ^ 2 + 3, x]
Out [4] = integrate [3 x] + to [x, x] integrate + integrate [x ^ 2, x]
Now we implement pattern that allows us to manage the integral of a constant
In [5]: = integrate [c_, x_]: = c x /; FreeQ [c, x]
Thus we obtain the following progress:
In [6]: = integrate [x + b x ^ 2 + 3, x]
Out [6] = 3 x + to integrate [x, x] + b integrate [x ^ 2, x]
Now we implement pattern that allows us to manage the integral of power
In [7]: = integrate [x_ ^ O_, x_]: = x ^ (n + 1) / (n + 1) /; FreeQ [n, x] & & n! = - 1
Thus we already reach the ultimate goal
In [8]: = integrate [x + b x ^ 2 + 3, x]
x ^ 2 b x ^ 3
Out[8]= 3 x + - + -
2 3
Note, that in this way a whole compact theory of integration could be built.
Exercise 5-12. Using standards, implement functions that select the first and last
items in one list either.
In [9]: first = [{x_, y_ _ _}]: = x