118 23 5MB
English Pages [217] Year 2024
Synthesis Lectures on Engineering, Science, and Technology
Erik Cuevas · Alberto Luque · Héctor Escobar
Computational Methods with MATLAB®
Synthesis Lectures on Engineering, Science, and Technology
The focus of this series is general topics, and applications about, and for, engineers and scientists on a wide array of applications, methods and advances. Most titles cover subjects such as professional development, education, and study skills, as well as basic introductory undergraduate material and other topics appropriate for a broader and less technical audience.
Erik Cuevas · Alberto Luque · Héctor Escobar
Computational Methods with MATLAB®
Erik Cuevas University of Guadalajara Guadalajara, Jalisco, Mexico
Alberto Luque University of Guadalajara Guadalajara, Jalisco, Mexico
Héctor Escobar University of Guadalajara Guadalajara, Jalisco, Mexico
ISSN 2690-0300 ISSN 2690-0327 (electronic) Synthesis Lectures on Engineering, Science, and Technology ISBN 978-3-031-40477-1 ISBN 978-3-031-40478-8 (eBook) https://doi.org/10.1007/978-3-031-40478-8 © The Editor(s) (if applicable) and The Author(s), under exclusive license to Springer Nature Switzerland AG 2024 This work is subject to copyright. All rights are solely and exclusively licensed by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use. The publisher, the authors, and the editors are safe to assume that the advice and information in this book are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or the editors give a warranty, expressed or implied, with respect to the material contained herein or for any errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional claims in published maps and institutional affiliations. This Springer imprint is published by the registered company Springer Nature Switzerland AG The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
Preface
The objective of this book is to present a comprehensive and consistent overview of numerical methods for undergraduate students and professionals in the engineering field. The book can also serve as a reference for engineering professionals who have the need to use MATLAB in their applications. This is because many of the MATLAB codes, presented after introducing the basic ideas of each algorithm, can be easily modified to solve similar problems even by those who do not know what goes on inside MATLAB routines and the algorithms they use. This book can be successfully used by two types of readers. The first type are those readers who require a detailed explanation of each algorithm and its potential. These readers are interested in knowing each method in such a way that they can modify the structure and make adaptations to solve their problems. The second are those readers who want to use numerical methods generically as subroutines. Just as most users of a household appliance need only know how to operate it to perform a task, these users need only know how to formulate their problems that they want to solve using MATLAB and how to use the corresponding routines to solve them. It is important to clarify that detailed knowledge of the numerical method is useful for finding a solution to a particular engineering problem. However, it is only implied that one-time users of any numerical method can use this book, as well as readers who want to understand the underlying principle/equations of each algorithm. This book focuses primarily on helping readers understand the fundamental mathematical concepts of numerical methods and practice problem-solving skills using MATLAB. The methodology of the book is to first teach basic concepts so that readers can correctly formulate problems mathematically, skipping some tedious and unnecessary checks. Then, readers can directly implement the codes in MATLAB to solve practical problems. All algorithms presented in this book are followed by a MATLAB code example so that students can easily modify the code to solve their own problems. This methodology is grounded in the belief that the majority of students and professionals, especially those with backgrounds outside of mathematics, recognize the paramount significance of effectively employing numerical tools to address their pertinent challenges. This practical application holds greater importance than considering only extensive demonstrations and proofs. v
vi
Preface
The book uses much more code than formal mathematics. This is because we are convinced that even readers with an excellent mathematical background have trouble understanding an approach until they see the algorithm implemented in code. This fact is because the implemented code removes all ambiguities. For more than two years, we have tried multiple ways to expose this material to dissimilar audiences. Along the way, we have counted on the invaluable tolerance of our students, mainly from CUCEI at the University of Guadalajara in Mexico. Special thanks are due to our fellow professors of the Centro Universitario de Ciencias Exactas e Ingenierías. So many collaborations, help and discussions with colleagues would merit an additional chapter. To all those mentioned, and especially to those omitted, our testimony of gratitude. Guadalajara, Mexico
Erik Cuevas Alberto Luque Héctor Escobar
Contents
1 MATLAB® Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.1 MATLAB® Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.2 MATLAB® Languaje . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.3 Trigonometric Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.4 Special Operators for Complex Numbers . . . . . . . . . . . . . . . . . . . 1.1.5 Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.6 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.7 Operators with Matrix and Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.8 Input and Output Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.9 Operators for Data Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.10 MATLAB® Relationship with Matrices and Vectors . . . . . . . . . . 1.1.11 Control Flow Structures in MATLAB® . . . . . . . . . . . . . . . . . . . . . 1.1.12 MATLAB® Function Declarations and .m Files . . . . . . . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1 1 2 4 6 6 6 7 7 8 8 9 10 15 16
2 Graphing with MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.2 Simple Graphing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.3 Contour of Two-Dimensional Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.4 Triangular Mesh and Contours . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.5 Surface and Mesh Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.6 Matlab as a Graphing Tool Implementing the Mapping Toolbox . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
19 20 20 34 38 41 46 56
3 Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.2 Matrices and Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.3 Matrix and Vector Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.4 Systems of Linear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.5 Determinant of a Square Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
57 57 58 60 62 63 vii
viii
Contents
3.6 Ill-Conditioned Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.7 Gaussian Elimination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.8 Gauss–Jordan Elimination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.9 LU Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.10 Eigenvalues of Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
65 67 70 72 73 75
4 Interpolation and Polynomials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.2 Polynomial Expressions in Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.3 Linear Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.4 Polynomial Interpolation with Power Series . . . . . . . . . . . . . . . . . . . . . . . . 4.5 Lagrange Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.6 Polynomial Interpolation Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.7 Differentiation and Integration of the Lagrange Interpolation Polynomial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.8 Chebyshev and Legendre Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.9 Cubic Hermite Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.10 Two-Dimensional Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
77 77 78 82 84 87 90 91 94 96 99 101
5 Numerical Differentiation Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.2 Differentiation of Interpolation Polynomials . . . . . . . . . . . . . . . . . . . . . . . . 5.3 Differences Approximation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.4 Differentiation by Taylor Expansion Method . . . . . . . . . . . . . . . . . . . . . . . . 5.5 Approximation of Differences in Partial Derivatives . . . . . . . . . . . . . . . . . 5.6 Numerical Computation of Higher-Order Derivatives . . . . . . . . . . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
103 103 104 106 107 108 109 111
6 Numerical Integration Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.1.1 Trapezoidal Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.1.2 Simpson’s Integration Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.1.3 Integration by Closed Newton–Cotes Formula . . . . . . . . . . . . . . . 6.1.4 Numerical Integration in Two-Dimensional Domains . . . . . . . . . 6.1.5 MATLAB® Commands for Numerical Integration . . . . . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
113 113 114 117 122 125 128 128
7 Roots of Nonlinear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.2 Graphical Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.3 Bisection Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
129 130 130 133
Contents
ix
7.4 Newton’s Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.5 Secant Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.6 Method of Successive Substitutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.7 Nonlinear Simultaneous Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
137 141 143 145 150
8 Spline Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2 Linear Splines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.3 Quadratic Splines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.4 Cubic Spline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.4.1 Cubic Splines with Standard Form Polynomials . . . . . . . . . . . . . 8.4.2 Cubic Splines Based on Lagrange Polynomials . . . . . . . . . . . . . . 8.5 Matlab Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
151 151 156 160 163 164 166 171 177
9 Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.2 Symbolic Solution of Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.3 Euler’s Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.4 Trapezoidal Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.5 Runge–Kutta Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.6 Predictor–Corrector Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.6.1 Functions for Generic Implementation . . . . . . . . . . . . . . . . . . . . . . 9.7 System of Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.8 Second Degree Differential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.9 Differential Equations with Boundary Value . . . . . . . . . . . . . . . . . . . . . . . . 9.10 Graphical Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
179 179 181 183 186 187 191 193 196 199 204 210 212
1
MATLAB® Fundamentals
Abstract
In this chapter, the fundamentals of MATLAB® are discussed. MATLAB® is a powerful scientific tool due to its ability to generate graphics and animations and its capacity to develop diverse complex applications. During this chapter, the environment, language, its relationship with matrices and vectors, control flow statemets and function declarations are discussed.
1.1
Introduction
MATLAB® is software originally written by Cleve Moler, with the goal of providing matrix software in the late 1970s. Over the years, the platform has developed to the extent that it is now a standard in engineering and computer science. MATLAB® is an interpreted, simple, yet fast and powerful language, coupled with its ability to generate graphics, incorporate animations, and its capacity for the development of diverse complex applications, and it has become a key tool in the advancement of scientific research. During this chapter, we will study the basic fundamentals of the environment and language itself that will allow us to understand, analyze and create codes that are presented in later chapters of the text.
© The Author(s), under exclusive license to Springer Nature Switzerland AG 2024 E. Cuevas et al., Computational Methods with MATLAB® , Synthesis Lectures on Engineering, Science, and Technology, https://doi.org/10.1007/978-3-031-40478-8_1
1
1 MATLAB® Fundamentals
2
1.1.1
MATLAB® Environment
The environment is the set of tools that allow you to work as a user or programmer. It allows importing and processing data, creating and modifying files, generating graphics and animations, and developing user applications. The MATLAB® interface is composed of different windows in which instructions can be executed or necessary information can be obtained from the workspace. Figure 1.1 shows the initial screen when the program is started: Depending on the need, instructions can be given in real time in the “command window” shown in Fig. 1.2 To obtain information on the variables with which you are working, you only need to consult the “workspace” window shown in Fig. 1.3 .
Fig. 1.1 MATLAB® main window
Fig. 1.2 MATLAB® command window
1.1
Introduction
3
Fig. 1.3 Workspace window
If you want to know the directory in which you are working, just check the “current folder” window shown in Fig. 1.4. In the case of creating a script in a new m-file, it will be necessary to click on the “ + ” button shown in Fig. 1.5 and select the script option. This will open the editor window Fig. 1.4 Current folder window
1 MATLAB® Fundamentals
4 Fig. 1.5 Button used to create a new script
Fig. 1.6 Function editor
shown in Fig. 1.6, which will be the area where we can edit and create the programs we want to carry out.
1.1.2
MATLAB® Languaje
1.1.2.1 Variable Assignment MATLAB® is a scientific programming language that, unlike many others, does not require a variable declaration to use variables. The only condition is the correct use of the following syntax: Variable_Name = Variable_Value
For example: A = 32
1.1
Introduction
5
Table 1.1 MATLAB® reserved words Reserved word
Function
Eps
Machine Accuracy (smallest number that can be expressed in the computer)
Flops
Floating point operations counter
Inf
Infinite
Pi
Pi number π
Nargin
Number of input arguments to the function
Nargout
Number of Output arguments in a Function
NaN
Not a number (occurs in mathematical indefinitions)
Date
Machine date
As MATLAB® is a scientifically oriented language, it is also necessary to take into account certain reserved words and predefined variables in the language, such as (Table 1.1).
1.1.2.2 MATLAB® Operators As you will see below, the fundamental units of MATLAB® are the matrices. Below are some operators that can be applied to both matrices and scalar quantities in the language (Table 1.2). In the case of operating with matrices, when is wanted to perform an operation element by element of the matrix just add a “.” Before the operator uses, for example, the sum element to element of matrices can be performed with: C = a.+ b
Table 1.2 MATLAB® arithmetical operators
Operator
Command
Add
+
Subtract
−
Multiplication
*
Division
/
Potentitation
^
Square root
sqrt()
Residue of a/b division
mod(a,b)
1 MATLAB® Fundamentals
6 Table 1.3 MATLAB® trigonometric operators
Operator
Command
Sine
Sin()
Cosine
Cos()
Tangent
Tan()
Cotangent
Cot()
Secant
Sec()
Cosecant
Csc()
Table 1.4 MATLAB ® Special operators for complex numbers Operador
Comando
Magnitude of a complex number
Abs(x)
Angle in radians of the complex number
Angle(x)
Generation of a complex number x + yi
Complex(x,y)
Conjugate of a complex number
Conj(x)
Real part of a complex number
Real(x)
Imaginary part of a complex number
Imag(x)
Returns 1 if the number is real or 0 if the number is complex
Isreal()
1.1.3
Trigonometric Operators
See Table 1.3.
1.1.4
Special Operators for Complex Numbers
See Table 1.4.
1.1.5
Relational Operators
They are operators that are generally used to evaluate a condition for which their output can be a 1 if the statement is true or a 0 if the statement is false (Table 1.5).
1.1
Introduction
Table 1.5 MATLAB® relational operators
7
Operador
Símbolo
Greater than
>
Less than
=
Less than or equal to
< =
Other than
~ =
Table 1.6 MATLAB® logical operators Operator
Command
Logical AND, gives a 1 as long as both conditions are true
&
Logical OR, gives 1 one provided that either of the two conditions is true
|
1.1.6
Logical Operators
These operators are typically used to evaluate more than one condition in a single condition sentence and are (Table 1.6).
1.1.7
Operators with Matrix and Arrays
Since the basic structure of MATLAB® is matrices, some special operators for matrix arrays are shown below (Table 1.7). Table 1.7 MATLAB® operators with matrix and arrays
Operator
Command
Dimension of an array
Size()
Length of a vector, or number of rows in a matrix Length() Maximum value of an array
Max()
Minimum value of an array
Min()
Median of the elements of an array
Median()
Average of the elements of an array
Mean()
Standard Deviation of the elements in an array
Std()
1 MATLAB® Fundamentals
8 Table 1.8 MATLAB® input and output operators Operator
Command
Displays the value of a variable on screen or a message in character format
disp(variable)or disp(‘mensaje’)
Used to display text and data program outputs on screen or to save them to a file
fprintf(variable)or fprintf(“mensaje”)
Receives numeric input from user keypad and stores it in Variable = input(prompt) a variable Receives keyboard string input and stores it in a variable
1.1.8
String = input(prompt,’s’)
Input and Output Operators
On several occasions, it is necessary to perform an interaction with the user of the code that is being executed, so it is necessary to have input data acquisition or message display instructions. In MATLAB® , these are the instructions (Table 1.8).
1.1.9
Operators for Data Analysis
MATLAB® can perform statistical analysis on columnar data sets, including the following functions (Table 1.9). Table 1.9 MATLAB® operators for data analysis
Operador
Comando
Correlation coefficient
Corrcoef(x)
Covariance matrix
Cov(x)
Cumulative Column Sum
Cumsum(x)
Cumulative Columns Product
Cumprod(x)
Histogram
Hist(x)
Maximum in each column
Max(x)
Sample interquartile range
Iqr(x)
Product of column elements
Prod(x)
Sum of column elements
Sum(x)
Range of each column
Range(x)
Variance of the sample
Var(x)
Frequency table of the vector
Tabulate(x)
Sort data in ascending order
Sort(x)
1.1
Introduction
9
Table 1.10 Commands for fast vector building Command
Function
(i:f)
Creates a vector with values from i to f in increments of 1
(i: s:f)
Creates a vector with values from i to f in increments or decrements of s
linspace(i,f)
Creates a linearly spaced vector between the values i and f with 100 elements
linspace(i,f,n)
Creates a linearly spaced vector with n elements
logspace(i,f)
Creates a logarithmically spaced vector between the values 10i to 10f with 50 elements
logspace(i,f,n)
Creates a logarithmically spaced vector between the values 10i to 10f with n elements
1.1.10 MATLAB® Relationship with Matrices and Vectors The fundamental unit in MATLAB® for working with and storing values in its variables is the matrix, hence the use of vectors, which are a special case of matrices. To create a vector, you enter the desired values separated by spaces or commas enclosed in square brackets “[]”. On the other hand, if you want to create a matrix, simply separate each row vector with the symbol “;”.
1.1.10.1 Access to Elements of Vectors and Matrices The way to access the elements stored in a vector is the use of an index so that “x(n)” would be the n-th element of the vector “x”. taking into account that unlike other languages such as C, in MATLAB® , the indexing of a vector starts counting from the value 1. It is also possible to access a set of elements of the vector in an ordered way using the operator “:” so that if we enter “x(i:f)”, we will access the set of elements comprising x(i) to x(f) in steps of one in the indexing. For a matrix, two values separated by a comma must be added in the indexing so that “x(f,c)” will return the element in row “f” and column “c” of the matrix we are working with.
1.1.10.2 Commands for Fast Vector Building In addition to defining a vector manually, it is sometimes necessary to create vectors with a larger number of elements, and the following commands can help save time in this task (Table 1.10).
1.1.10.3 Commands for Fast Array Building As with vectors, it is often necessary to create special matrices automatically; below are the commands that will help us to perform this action (Table 1.11).
1 MATLAB® Fundamentals
10 Table 1.11 Commands for fast array building Comando
Función
zeros(n)
Creates a square matrix of n x n in which all its values are zero
zeros(n,m) Creates a square matrix of n x m in which all its values are zero ones(n)
Creates a square matrix of n x n in which all its values are one
ones(n,m)
Creates a square matrix of n x m in which all its values are one
rand(n)
Creates a n x n square matrix of uniformly distributed random numbers with values between 0 and 1
rand(n,m)
Creates a n x m square matrix of uniformly distributed random numbers with values between 0 and 1
randn(n)
Creates a n x n square matrix of uniformly distributed random numbers with values between 0 and 1
randn(n,m) Creates a n x m square matrix of uniformly distributed random numbers with values between 0 and 1 eye(n)
Creates a n x n square matrix with ones on the diagonal and zeros on the remainder
magic(n)
Create a square matrix of n x n so that its rows and columns add up to the same values
1.1.11 Control Flow Structures in MATLAB® The flow control structures are those that allow us to execute or repeat certain segments of code depending on a given condition in MATLAB® .
1.1.11.1 Conditional If-Else Structure In MATLAB® , the conditional structure has the following syntax:
In this structure, when the condition is met, the first block of instructions is executed; otherwise, the second block is executed. It is not necessary to add the “else” statement
1.1
Introduction
11
in case you do not want to execute a specific block of instructions if the condition is not met. Example: Algorithm 1 Algorithm to detect even and odd numbers in MATLAB®
1.1.11.2 Selective SWITCH Structure This structure is used to replace multiple if-else conditions in which it is analyzed that a variable can take different values, and its syntax is:
12
1 MATLAB® Fundamentals
In this case, the variable may have different values, and the code segment that fits the indicated case will be executed. In case it does not fit in any of the previously indicated cases, the default instruction defined in the statement “otherwise” will be executed. Example: Algorithm 2 Algorithm that emulates a selection of arithmetic operations in MATLAB®
1.1
Introduction
13
1.1.11.3 Cyclic Structure While This structure is used when you want to repeat the same code segment several times. To be executed, the structure checks a condition and carries out the instructions as long as this condition is met. Its syntax is: while (condition) Instructions end
1 MATLAB® Fundamentals
14
One of the most commonly used tricks in this statement is to repeat the loop infinitely by replacing the condition input with a “1”. It is also possible to interrupt the loop and exit the loop at any time by using the “break” statement. Example: Algorithm 3 Algorithm that performs the calculation of the factorial of a number given by the user in MATLAB®
1.1.11.4 Cyclica Structure For This structure is an alternative to the “while” statement in which, in an analogous way, a code segment can be repeated a certain number of times and, in addition, the parameters of cycle start, cycle end and increment in the cycle interval can be defined from its call. Depending on the way it is programmed, the increment or decrement value in the cycle interval can be chosen or not. Its syntax is:
for variable = initial_value : final_value Instructions end
1.1
Introduction
15
In this way, the cycle will repeat whenever the variable has values from “start” to “end”, and the increment interval in the variable will be “1”. Another way to use this structure is: for variable = initial_value :increment_value : final_value Instructions end
In this alternative way, one will be able to define the increment value that one wishes the variable to be evaluated to take. Example: Algorithm 4 Algorithm that displays the desired number of terms of the Fibonacci sequence in MATLAB®
1.1.12 MATLAB® Function Declarations and .m Files There are two types of “.m” files in MATLAB® , command or script files and function statement files. The command file simply has a set of instructions to be executed when the file name is entered on the MATLAB® command line or the name is included in
16
1 MATLAB® Fundamentals
some other “.m” file. On the other hand, the function files allow us to define functions analogous to those of MATLAB® in which it is possible to include name, input and output arguments to make use of them later in future scripts.
1.1.12.1 Function Declaration in MATLAB® When declaring functions, it is of vital importance to save the “.m” file with the same name given to the declared function. The syntax for declaring functions in MATLAB® is the following:
Here, it is possible to notice how the first line starts with the “function” statement followed by the output arguments [out1,out2,…,outN] enclosed in square brackets (in case of having only one output argument, it can be declared without enclosing it in square brackets). Once this is done, the desired name of the function to work with is placed next to its input arguments (ina1,ina2,…,inaN) enclosed in parentheses. After that, we write the commands that lead us to obtain the output arguments previously mentioned, and the output of the function is a vector with the values of the output variables ordered in the way it was declared at the beginning of the function.
References 1. MATLAB¨/Simulink¨ Essentials: MATLAB¨/Simulink¨ for Engineering Problem ... -Sulaymon L. Eshkabilov—Google Libros. https://books.google.com.mx/books?hl=es&lr=&id=wVh 8DgAAQBAJ&oi=fnd&pg=PA1&dq=MATLAB+and+simulink+for+engineers&ots=o5U OvPgbSY&sig=a4hxx4GiThsF1hV24JpMLfa8F-Q&redir_esc=y#v=onepage&q=MATLAB% 20and%20simulink%20for%20engineers&f=false (accessed May 30, 2023). 2. H. Moore, “MATLAB for Engineers,” 2012, Accessed: May 30, 2023. Available: https://ds. amu.edu.et/xmlui/bitstream/handle/123456789/5248/MATLAB%20for%20Engineers%203rd% 20ed.%20-%20H.%20Moore%20%28Pearson%2C%202011%29%20BBS.pdf?sequence=1& isAllowed=y.
References
17
3. L. Keviczky, R. Bars, J. Hetthéssy, and C. Bányász, “Introduction to MATLAB,” Advanced Textbooks in Control and Signal Processing, pp. 1–27, 2019, doi: https://doi.org/10.1007/978-98110-8321-1_1. 4. D. M. Etter and U. Saddle River Boston Columbus San Francisco New York Indianapolis London Toronto Sydney Singapore Tokyo Montreal Dubai Madrid Hong Kong Mexico City Munich Paris Amsterdam Cape Town, “Introduction to MATLAB,” 2002, Accessed: May 30, 2023. [Online]. Available: https://www.pearsonhighered.com/assets/preface/0/1/3/6/0136081231.pdf. 5. E. A. Sobie, “An introduction to MATLAB,” Sci Signal, vol. 4, no. 191, Sep. 2011, doi: https:// doi.org/10.1126/SCISIGNAL.2001984. 6. T. Michalowski, “Applications of MATLAB in Science and Engineering,” 2011, Accessed: May 30, 2023. [Online]. Available: https://books.google.com/books?hl=es&lr=&id=qn-ZDwAAQ BAJ&oi=fnd&pg=PR11&dq=MATLAB+and+simulink+for+engineers&ots=KqUKAFMF1h& sig=vGDChrUonRY17vL8kR4wOK78A0k. 7. D. Xue and Y. Chen, “System simulation techniques with MATLAB and Simulink,” 2013, Accessed: May 30, 2023. [Online]. Available: https://books.google.com/books?hl=es&lr=&id= 6d7iAAAAQBAJ&oi=fnd&pg=PT6&dq=MATLAB+and+simulink+for+engineers&ots=w6P KsMDIBQ&sig=crq_xM3YFZOY8k7FZaPFjTEt57k. 8. “Applications of MATLAB in Science and Engineering - Google Libros.” https://books.google. com.mx/books?hl=es&lr=&id=qn-ZDwAAQBAJ&oi=fnd&pg=PR11&dq=MATLAB+and+sim ulink+for+engineers&ots=KqUKAFMF1h&sig=vGDChrUonRY17vL8kR4wOK78A0k&redir_ esc=y#v=onepage&q=MATLAB%20and%20simulink%20for%20engineers&f=false (accessed May 30, 2023).
2
Graphing with MATLAB
Abstract
The relationship between calculations and graphics in computing was nearly nonexistent in the past, leaving computational users to rely solely on numerical listings to evaluate research outcomes. However, with significant technological advancements, researchers, engineers, and professionals from various domains can now easily integrate graphs into their work and research. The importance of incorporating graphs has been recognized throughout our educational journey, from basic to advanced levels, and this significance extends to various fields of knowledge, including biology, applied mathematics, and evolutionary computation. Graphs find direct application in scientific and technological works, aiding in analyzing research findings, mathematical evaluations, and presentations. Graphs have become an essential tool in research, as they provide a different perspective and facilitate evaluating research results. MATLAB stands out among the widely used software for generating high-quality and precise graphs due to its ability to produce visually striking graphs with just a few simple commands. In Sect. 2.1, a short introduction to the chapter is given. Section 2.2 describes the essential elements of graphing with MATLAB software. Section 2.3 presents the implementation of different commands to plot the contour of two-dimensional functions. Likewise, Sect. 2.4 reviews the most important features of MATLAB to create a triangular mesh. Section 2.5 gives an overview of the combined plots, and Sect. 2.6 The Mapping Toolbox is implemented in creating maps, manipulating satellite images, and creating a 3D globe.
© The Author(s), under exclusive license to Springer Nature Switzerland AG 2024 E. Cuevas et al., Computational Methods with MATLAB® , Synthesis Lectures on Engineering, Science, and Technology, https://doi.org/10.1007/978-3-031-40478-8_2
19
20
2.1
2 Graphing with MATLAB
Introduction
Visualizing complicated mathematical functions graphically in up to 3 dimensions and not having a tool to develop such graphs complicates understanding them [1]. The importance of implementing graphs has been supported from our basic education to more advanced stages. This same importance is present in various areas of knowledge, such as biology, applied mathematics, and evolutionary computation. We can identify a direct application of graphs by associating them to works carried out in any area of science and technology, some mathematical analysis developed or simply in some presentation within our work environment. In past decades, the relationship between calculations and graphics in computing was almost nonexistent, forcing computational users to evaluate results from research developed only in numerical listings. Nevertheless, with the boom that has occurred to date, technological development has changed radically, allowing researchers, engineers or anyone who develops a different work to implement graphics in their work and research easily. Currently, graphs in the research area are of obligatory use since they provide a different perspective at the moment of the evaluation of research results. One of the most common software programs in this area is the MATLAB computer program since striking and precise graphing can be performed with only a few commands. Understanding and developing mathematical equations through graphs is a simple and pleasant way to learn mathematics. Therefore, it is recommended that any mathematical function or the result of an analysis found in this book be graphed to obtain a better understanding of it. Finally, it is recommended that once the graph analysis is finished, it should be eliminated in the same way as the implemented variables since MATLAB could present problems when implementing certain commands. If the problems persist, it is recommended to restart the program and try to execute the instruction again.
2.2
Simple Graphing
In the MATLAB graphing environment, to make a plot, we use the plot command, which requires two variables, x and y, as arguments. These variables represent the position of a set of data, so these variables must constitute an identical arrangement of rows or columns of the same length. For example, suppose that we want to plot the function f (x) = cos(x)ex p(−0.4x), 0 ≤ x ≤ 10, which is shown in Fig. 2.1 and plotted with code 2.1.
2.2
Simple Graphing
21
Fig. 2.1 Graphic of code 2.1 or 2.2
Code 2.1 x=(0:0.05:10); y=cos(x).*exp(-0.4*x); plot(x,y) xlabel('x'); ylabel('y')
Column vectors can also be implemented and established in the plot command arguments, as shown in code 2.2.
Code 2.2 x=(0:0.05:10)'; y=cos(x).*exp(-0.4*x); plot(x,y) xlabel('x'); ylabel('y')
22
2 Graphing with MATLAB
Fig. 2.2 Graphic of code 2.3
The two previous codes provide the same plot presented in Fig. 2.1. The axis labels are established under the xlabel and ylabel commands, which will be explained in more detail later. Figure 2.2 shows the graph from code 2.3, constituted by a series of points connected in a complex plane.
Code 2.3 x=(0:0.05:8*pi); y=(sin(-x)+i*sin(-2*x)).*exp(-0.05*x)+0.01*x; plot(real(y), imag(y)) xlabel('Re(y)'); ylabel('Im(y)')
Among the possibilities available at the time of plotting, it is possible to implement a plot with different symbols without being connected by lines [2]. Implementing this function is required to give one more argument to the plot function, which is set after the coordinates. The available types of marks are ‘.’, ‘+’, ‘*’, ‘o’ and ‘x’. These symbols are dots, plus, stars, circles and x marks, respectively (Fig. 2.3).
2.2
Simple Graphing
23
Fig. 2.3 Graphic of code 2.4 with circle symbols only
Code 2.4 x=(0:0.3:10)'; y=cos(x).*exp(-0.4*x); plot(x,y,'o') xlabel('x'); ylabel('y' )
To be able to plot a graph with both lines and symbols, it is only necessary to plot a second time. This behavior can be implemented in the same line of code in the plot command, so the code in code 2.4 would look like this: plot(x,y,x,y,‘o’). The default line type set is continuous, but MATLAB allows plotting on different line types and the option to specify a color for the line type.
24
2 Graphing with MATLAB
TYPE OF LINE
SYMBOL
SOLID
-
DASHE
--
DOTTED
DASHES- DOTS
LINE COLOR
SYMBOL
RED
r
YELLOW
y
MAGENTA
m
TURQUOISE
c
GREEN
g
BLUE
b
WHITE
w
BLACK
k
: -.
After the coordinates plot(x,y,‘–’), the desired line type must be added to stipulate with the command plot command a different line from the default one. In the same way, when you want to implement a different line color, you should stipulate it in the plot command followed by the coordinates plot(x,y,‘r’). Combining both modifications, the symbols and colors are also possible. Specifying it in the plot command is necessary after the coordinates plot(x,y,‘or’); this line of code will return a plot with red symbols. An alternative to the plot command is the fplot command, which is implemented as follows: fplot(‘fun name’,[xmin, xmax]). where fun name refers to the name of the MATLAB file or the name of the function to be plotted, xmin refers to the minimum limit of the plot, and xmax refers to the maximum limit of the plot. These limits are considered the actual minimum and maximum of the function, but this can be adjusted with the command axis. The command clf removes all existing information in the plot windows, while the cla command removes the previously plotted curves and redraws the axes. On the other hand, there are functions in the implicit state, for example, y 3 + exp(y) = tanh(x). This prevents a correct plotting since it is impossible to express y as a function of x or x as a function of y. However, it is possible to plot the function thanks to the contour command. The plotting values, such as the scale marks, the minimum and maximum coordinates and the values of the coordinates in the scale marks, are set automatically. However, we can modify the minimum and maximum coordinates and the frame’s shape thanks to the axis command. Therefore, we obtain a square-shaped graph with the axis(‘square’) command, as shown in Fig. 2.4. Another alternative is the axis command; this instruction removes the scale marks and coordinates axes by specifying the word off, axis(‘off’). T his effect can be reversed at any time by implementing the counterpart of the previous command, axis(‘on’). The minimum
2.2
Simple Graphing
25
Fig. 2.4 Plot with axis(‘square’) command
and maximum coordinates within the plot can be implemented in a specific way using the axis command ([xmin, xmax, ymin, ymax]). This code will cut the lines that could go out of the established limits. This command is implemented after the plot command to modify the display of the plot as many times as desired. For example, the reader is encouraged to implement the axis([−1.5, 4, −0.9, 0.9]) command in code 2.4. MATLAB can add a grid to the graph by implementing the grid on command (as shown in Fig. 2.5). While the grid off command removes the grid, the implementation of the grid command alone toggles between displaying or not displaying the grid.
Code 2.5
x=(0:0.1:10); y=cos(x).*exp(-0.4*x); plot(x,y,'k') grid on xlabel('x'); ylabel('y')
26
2 Graphing with MATLAB
Fig. 2.5 Graphic with command grid on
Code 2.6
x=(0:0.01:pi+1); y=sin(7*x).*exp(-0.1*x); polar(x,y,'k') grid on
The polar command allows graphing a function in polar coordinates; an example is code 2.6, which graphs Fig. 2.6. The graphs can also be displayed on a logarithmic and semilogarithmic scale with the loglog command, as illustrated in code 2.7 and Fig. 2.7.
2.2
Simple Graphing
Fig. 2.6 Graphic with polar command
Fig. 2.7 Graphic implementing loglog command
27
28
2 Graphing with MATLAB
Code 2.7
t=(0.01:0.1:5); x=exp(t); y=exp(t.*sinh(t)); loglog(x,y) grid on xlabel('x'); ylabel('y')
Code 2.8 results in a semilogarithmic plot with the y-axis on the logarithmic scale.
Code 2.8
t=(.1:.1:3); semilogy(t, exp(t.*t)); grid on xlabel('t'); ylabel('t.*t')
In the same way, code 2.9 produces a semilogarithmic plot with the x-axis on the logarithmic scale.
Code 2.9
t=(.1:.1:3); semilogx(t, exp(t.*t)); grid on xlabel('t'); ylabel('t.*t')
All coordinate pairs are written in the command to plot different curves in a single plot command. Additionally, a different color or mark should be assigned to each curve for practical purposes. This change is indicated after the pair of coordinates, as shown in Fig. 2.8, a product of code 2.10.
2.2
Simple Graphing
29
Fig. 2.8 Graphic implementing the plot command with two curves
Code 2.10
x = 0:0.05:5; y = sin(x); z = cos(x); plot(x,y,'k-',x,z,'k*')
We have implemented the plot command to plot two different curves, but sometimes it is necessary to plot an additional curve on top of another previously plotted curve. This addition is performed using the hold-on command. Once the command is stipulated in the code, the plot remains on the screen even if another code block is executed. Therefore, executing the hold-off command is necessary when the desired procedure is finished. The above can be visualized in code 2.11, shown graphically in Fig. 2.9.
30
2 Graphing with MATLAB
Fig. 2.9 Graphic implementing hold on and hold off commands
Code 2.11
x = 0:0.05:5; y = sin(x); plot(x,y,'k-') hold on z = cos(x); plot(x,z,'kx') hold off
At the moment of having different curves, thanks to the hold-on command, it is necessary to stipulate the different minimum and maximum of the coordinates in the graph. This property, as we saw before, is codified with the axis command; if the minimum and maximum are not stipulated, MATLAB will determine them by default and based on the first graph shown, which can bring several problems at the moment of visualizing the second curve. The hold-on command also has a very important function when preparing a graphic that takes a long time to be displayed. When commands are implemented to redesign the
2.2
Simple Graphing
31
parameters of the figure to be displayed, such as the perspective angles, the color map or the color axis, among others, to make these modifications, it is necessary to redraw the entire figure. To save time, all the modification commands are issued first, and then the plot command is implemented. We can also stipulate different titles or texts to the coordinates of the figure using the xlabel, ylabel and title commands. In addition, placing text inside the graph with the text or gtext command is possible. The first command requires three arguments for its correct operation, and the first two values are the coordinates where we want the text to start. The last argument refers to the text string we want to display in the graph, which can be a predefined string or a variable. When we want to include different titles or texts in our graph, we can implement the num2str and int2str commands. These commands allow us to convert numbers to character strings to display in titles or texts. For example, string = num2str(pi) allows us to obtain a string containing 3.1416. On the other hand, string = int2str(pi) will return a string containing only the integer part of the number, in this case, 3. Once we have the string, we can include it in the title command as follows: title [‘number =’, string]. This example can be clarified with code 2.12 and Fig. 2.10.
Fig. 2.10 Graphic implementing the commands title, text, and gtext
32
2 Graphing with MATLAB
Code 2.12
x = (0:0.01:1)';k = 1.4; y = (1+(k-1)/2+x.^2).^(k/(k-1)); plot(x,y) xlabel('x-axis'), ylabel('y-axis') title('Title set for the graph')
When it is necessary to specify the coordinates in a more guided way, it would be appropriate to implement the gtext command since it allows you, once the graphic is finished, to use a pointer with which it is possible to display the text indicated in the position where it is clicked. The text command can be implemented in three-dimensional axes. Otherwise, the gtext command can only be used in two-dimensional axes. We can modify the font and color by implementing the following code text (2, 0, ‘abcdef’, ‘FontName’, ‘Color’). The color of the text can vary between red, yellow, green, cyan, blue and magenta, which can be implemented in the code as r, y, g, c, b, and m, respectively, concerning the font size change depending on the MATLAB edition. The text command also offers us the possibility to convert the stipulated letters into Greek letters. This change is implemented with the argument‘symbol’ followed by the argument ‘FontName’. The size of the axes can be modified by implementing the set command, and the only drawback is that if the text is placed in the wrong place, there is no way to delete it. The figure will have to be redrawn after correcting the code. MATLAB allows us to implement subplots with the subplot command. Using this command, we can display m by n plots in a single figure, where m, n and k are integers, m and n refer to an array of plots, and k refers to the sequential number of the plot. The above is illustrated in Fig. 2.11 and code 2.13.
Code 2.13
x = 0:0.3:30; subplot(2,2,1),plot(x, sin(x),'k'), title('Subplot 2,2,1') xlabel('x'), ylabel('sin(x)') subplot(2,2,2),plot(x,x.*sin(x),'k'), title('Subgraph 2,2,2') xlabel('x'), ylabel('x.*sin(x)') subplot(2,2,3),plot(x,x.*sin(x).^2,'k'), title('Subplot 2,2,3') xlabel('x'), ylabel('x.*sin(x).^2') subplot(2,2,4),plot(x,x.^2.*sin(x).^2,'k'), title('Subplot 2,2,4') xlabel('x'), ylabel('x.^2*sin(x).^2')
2.2
Simple Graphing
33
Fig. 2.11 Graphic where subgraphs are implemented
The plot3 command allows us to plot in three dimensions. All the rules we have seen for the plot command can be implemented with plot3. In Fig. 2.12, we can observe the spiral movement of a particle from an initial point to an endpoint implemented with the plot3 command. The viewing angle can be modified with the view command or the axis command to define the space limits. The command plot3 is implemented in code 2.14.
Code 2.14
t = 0:0.1:20; r = exp(-0.2*t); th = pi*t*0.5; z = t; x = r.*cos(th); y = r.*sin(th); plot3(x,y,z,'k') hold on plot3([1,1], [-0.5,0], [0,0],'k') text(1, -0.7, 0 ,'Start') n = length(x); text(x(n), y(n), z(n)+2, 'Final') xlabel('X'); ylabel('Y'); zlabel('Z');
34
2 Graphing with MATLAB
Fig. 2.12 Graphic implementing the plot3 command
2.3
Contour of Two-Dimensional Functions
In code 2.15, we implement a MATLAB function using the meshgrid command, which allows us to create two-dimensional arrays of the form (x,y), where x is an array of the x-coordinates of the grid and y is an array of the y-coordinates of the grid. The arrays mentioned above are necessary to calculate a two-dimensional z-array (Fig. 2.13).
Code 2.15
xa = -2:0.2:2; ya = -2:0.2:2; [x,y] = meshgrid(xa, ya); z = x.*exp(-x.^2-y.^2); mesh(x,y,z) title('This is a 3-D graph of z = x * exp(-x^2 - y^2)') xlabel('x'); ylabel('y'); zlabel('z');
2.3
Contour of Two-Dimensional Functions
35
Fig. 2.13 Graphic implementing the mesh command
Among the tools offered by MATLAB, we have the contour command, which allows us to plot the contour of a function contained in a two-dimensional array. The tool is implemented with the command contour(x, y, z, level). Within the command, the argument z represents the two-dimensional array of the function, and the x and y values constitute the x and y coordinates in the array. Finally, the level parameter refers to the contour levels contained in a vector. The x and y parameters can also be one-dimensional arrays, so the first index of z rotates or changes direction relative to the y value. Otherwise, the second index rotates or changes direction relative to the x value. If the mesh is equispaced, then for convenience, it is possible to implement only the contour(z) function. It is also possible to replace the level argument with an integer c, which is the number of levels. These levels are obtained by dividing the maximum and minimum z values into m − 1 intervals.
36
2 Graphing with MATLAB
Code 2.16
axis('square') xm=-2:.2:2; ym=-2:.2:2; [x,y]=meshgrid(xm, ym); z=x.*exp(-x.^2-y.^2); zmax=max(max(z)); zmin=min(min(z)); dz=(zmax-zmin)/10; level = zmin + 0.5*dz:dz:zmax; h=contour(x,y,z, level,'edgecolor','k'); clabel(h,'manual') title('Contour plot made with contour(x,y,z, level)') xlabel('x'); ylabel('y')
The result of code 2.16 can be seen in Fig. 2.14, in which the function implemented for its graphing is defined in a two-dimensional function. The contours of the plotted figure are drawn with the command clavel(h,‘manual’). This function enables the programmer to specify the position of the numbers with the pointer. The contour levels can be drawn automatically with clavel(h). This behavior can be identified in Fig. 2.15.
2.3
Contour of Two-Dimensional Functions
Fig. 2.14 Graphic implementing contour command with level location
Fig. 2.15 Graphic implementing contour command with automatic levels
37
38
2.4
2 Graphing with MATLAB
Triangular Mesh and Contours
A triangular mesh has geometrically triangular elements, and its simplest implementation is in finite element analysis [3]. To implement a triangular mesh, two data sets must be used, one with the numbering of the elements and the second with the numbering of the points. These files will be structured as follows:
In addition, a function will be integrated that will implement the data files mentioned above. This function will generate the triangular mesh, and it is presented as follows:
2.4 Triangular Mesh and Contours
Triangular_mesh.m
function triangular_mesh(data_elem, coord_point, scale) hold off [n_tr,n]=size(data_elem); [n_pt,n]=size(coord_point); nmax=data_elem(1,1); x=coord_point(:,2); y=coord_point(:,3)*scale; element_number=input('Do you want to number the elements? 1 yes/0 no:'); points_number=input('Do you want to number the elements? 1 yes/0 no:'); xmin=min(x); xmax=max(x); x_cen=0.5*(xmin+xmax); ymin=min(y); ymax=max(y); y_cen=0.5*(ymin+ymax); Dx=xmax-xmin; Dy=ymax-ymin; if DxDy, ymin=y_cen-Dx/2; ymax=y_cen+Dx/2; end clf; hold off; clc; axis([xmin, xmax,ymin, ymax]) xlabel('Triangular mesh plot'); hold on del_x=0.1; del_y=0.1; for k=1:n_tr for l=1:3 p=data_elem(k,l+1); xx(l)= x(p); yy(l)=y(p); end xx(4)=xx(1); yy(4)=yy(1); plot(xx, yy) x_cen=sum(xx(1:3))/3; y_cen=sum(yy(1:3))/3; if element_number == 1 text(x_cen - del_x, y_cen-del_y, int2str(k)) end end if points_number == 1 for n=1:n_pt text(x(n), y(n), ['(',int2str(n),')']) end end axis('off')
39
40
2 Graphing with MATLAB
A main file described in code 2.17 is created to integrate the function described above and the data defined in the point and element files (Figs. 2.16 and 2.17).
Fig. 2.16 Triangular mesh highlighting numbered elements
Fig. 2.17 Triangular mesh numbering only the points
2.5
Surface and Mesh Plotting
41
Code 2.17
load elements.m load points.m triangular_mesh(elements, points, 1.8)
2.5
Surface and Mesh Plotting
Three-dimensional graphics will be discussed and analyzed in this section. This type of graphics has been improved over time due to the new versions of MATLAB that have been released. Previously, we discussed the mesh command. However, we will discuss it in more detail in the following pages. When referring to a mesh plot of a matrix, it is necessary to remember that one of the most common applications of three-dimensional graphics is precisely the plotting of a matrix, considering an m by n matrix x. This plot can be plotted with code 2.18 and visualized in Fig. 2.18.
Fig. 2.18 Mesh graph of a matrix
42
2 Graphing with MATLAB
Fig. 2.19 Implementation of the view command with different perspectives
Code 2.18
for i=1:8 for j=1:7 x(j,i)=sqrt(i^2+j^2); end end mesh(x,'edgecolor','k') xlabel('i') ylabel('j') zlabel('z')
Within the three-dimensional plot, the limits implemented in the three-dimensional space of the plot are automatically weighted, but depending on the application to which you want to orient this can be modified with the axis command [xmin, xmax, ymin,
2.5
Surface and Mesh Plotting
43
ymax, ymax, zmin, zmax], this command structure is logically inherited from the twodimensional plots. Likewise, the x-, y-, and z-axis legends are added in the usual way with xlabel, ylabel, and zlabel, respectively. A very important aspect of three-dimensional graphics is the perspective the user can take to visualize the graphic. This perspective can be modified with the command view ([azimuthal, elevation]) or view ([x, y, z]). Within the above structure, azimuthal represents the azimuthal angle, and the elevation argument represents the elevation angle. It should be noted that when the azimuthal and elevation values are 0, the user’s perspective is at the reference perspective angle, which is located along the negative y-axis. From this perspective, the three-dimensional graph becomes a two-dimensional plane, with the zaxis vertically and the x-axis extending horizontally to the right. Modifying the azimuthal parameter allows us to move the perspective position in a counterclockwise azimuthal degree around the z-axis from the reference angle. To complete the command analysis, the elevation parameter will enable us to raise the perspective angle elevation degrees from the x–y plane. By not specifying the azimuthal and elevation values, the default values are −37.5° and 30°, respectively. With the implementation of the view command by giving it three-dimensional coordinates as parameters such as view([x, y, z]), it is assumed that the user’s perspective is along the vector [x, y, z] along the origin. view([0, −1, 0]) is equivalent to view([0, 0]) expressed in angles. This implementation can be seen in code 2.19 and visualized graphically in Fig. 2.19.
Code 2.19
yp=1:5; xp=1:4; [x,y]=meshgrid(xp, yp); z=sqrt(x.^2+y.^2); %subplot 1 subplot(221) mesh(x,y,z,'edgecolor','k')
44
2 Graphing with MATLAB
axis([0,5,0,5,5,0,10]) title('Default perspective') xlabel('X-axis') ylabel('Y axis') zlabel('Z-axis') %subplot 2 subplot(222) mesh(x,y,z,'edgecolor','k') axis([0,5,0,5,5,0,10]) title('Perspective [40,25]') view([40,25]) xlabel('X-axis') ylabel('Y axis') zlabel('Z-axis') %subplot 3 subplot(223) mesh(x,y,z,'edgecolor','k') axis([0,5,0,5,5,0,10]) title('Perspective [70,15]') view([70,15]) xlabel('X-axis') ylabel('Y axis') zlabel('Z-axis') %subplot 4 subplot(224) mesh(x,y,z,'edgecolor','k') axis([0,5,0,5,5,0,10]) title('Perspective [0,0]') view([0,0]) xlabel('X-axis') ylabel('Y axis') zlabel('Z axis')zlabel('z')
Another element that needs to be addressed is the contour with mesh. Implementing the meshc command allows plotting the contour of z in the x and y planes in addition to the mesh(z) plots. The above is referenced in code 2.20 and Fig. 2.20.
2.5
Surface and Mesh Plotting
45
Fig. 2.20 Implementation of the meshc command
Code 2.20
dth=pi/20; j=1:21; i=1:10; x=log(i); y=log(j); [x,y]=meshgrid(x,y); z=sqrt(0.1*((x-log(5)).^2+(y-log(5)).^2))+1; meshc(x,y,z,'edgecolor','k') view([41,27]) xlabel('Axis X') ylabel('Y-axis') zlabel('Axis z')
An important utility of the hold on command is found within the implementation of graphics that take time to be displayed because when the properties are modified, either of the color map, the color axis or even the same axis, in addition to other parameters that can be implemented after having made the figure, but if another command that performs
46
2 Graphing with MATLAB
some of the modifications mentioned above is used after plotting the figure, the figure is redrawn. Therefore, it saves considerable time to indicate the necessary configurations with their respective commands before plotting and is retained with the hold on.
2.6
Matlab as a Graphing Tool Implementing the Mapping Toolbox
Within the possibilities offered by MATLAB, we address an embedded feature within the mapping toolbox [4]. This toolbox will allow us to plot a set of structured data and visualize them in the form of city maps or world maps, depending on the data we have. In addition, we can implement satellite images to point out through legends or signals specific points to locate important cities inside a country or the outstanding colonies of certain towns. Additionally, these graphing maps will be manipulated to orient them to an application. In addition, the mapping toolbox allows the generation of animated globes. This exercise will be discussed in more detail in its respective section. The type of file needed to plot is the shapefile format. These file types contain geospatial data vectors for geographic information software and are identified by their ‘.shp’ ending. Shapefiles specify a vector of spatial features such as points, lines and polygons, which are implemented to represent lakes, rivers and others. Each element usually has attributes that describe it, such as a name or its temperature. This type of file can be obtained from the following web page https://la.mathworks. com/help/map/finding-vector-geodata.html. However, it is not subject to only being able to implement such data. In code 2.21, the mapshow() function is implemented, which displays the coordinates of the x and y vectors as lines.
Code 2.21
streets = shaperead('concord_roads.shp'); figure mapshow(streets); xlabel('East in meters') ylabel('North in meters')
In code 2.21, the shaperead() function is used to read the shapefile and assign it to a variable named ‘roads’, which will be the argument of the mapshow function. Finally, the names of the x and y-axes are specified, which can be identified in Fig. 2.21. As in the two-dimensional or three-dimensional graphics, we can also modify the style of the
2.6
Matlab as a Graphing Tool Implementing the Mapping Toolbox
47
Fig. 2.21 Graphing implementing the mapshow function
lines of our map by specifying the word LineStyle followed by its parameter within the mapshow function, as we can see in code 2.22 and appreciate graphically in Fig. 2.22.
Code 2.22
figure mapshow('concord_roads.shp','LineStyle',':'); xlabel('East in meters') ylabel('North in meters')
Another way to graphically display maps with the help of mapping toolbox is the inclusion of geospatial images, which allow us to visualize the satellite image of a specific area and display labels indicating areas of interest. Code 2.23 shows the implementation of GeoTIFF files, which can store and transfer satellite images, elevation models and scanned maps. These files have embedded data in tags that can be implemented when locating an area of interest (Fig. 2.23).
48
Fig. 2.22 Modifying the line style with the mapshow function
Fig. 2.23 Data plot boston.tif
2 Graphing with MATLAB
2.6
Matlab as a Graphing Tool Implementing the Mapping Toolbox
49
Code 2.23
figure mapshow boston.tif axis image manual off S = shaperead('boston_placenames.shp'); surveyFeetPerMeter = unitsratio('sf','meter'); for k = 1:numel(S) S(k).X = surveyFeetPerMeter * S(k).X; S(k).Y = surveyFeetPerMeter * S(k).Y; end text([S.X], [S.Y], {S.NAME}, 'Color', [0 0 0], 'BackgroundColor',[0.9 0.9 0],'Clipping','on');
A feature of interest is to visualize in three-dimensional form a globe. For this, we will establish the perspective that it will have. We use some commands such as axesm, which allows us to create the access map and has a property called ‘globe’; gridm provides the access map with various features such as line style and color, among others. The spin function is used to give the globe the ability to rotate. The spin function is shown below.
SPIN.M
for i=90:-5:-270 view(i,23.5); drawnow end
The next objective will be to provide the globe with a solid color for the base, then proceed to plot the globe to finally add the lighting touches and some perspective adjustments, to the procedure described above can be followed with code 2.24 and observe the result graphically in Fig. 2.24.
50
2 Graphing with MATLAB
Fig. 2.24 Graphing of a globe
Code 2.2
figure axesm('globe'); gridm('GLineStyle','-','Gcolor',[.7 .8 .9],'Grid','on') %% Rotate the globe once only set(gca,'Box','off','Projection','perspective') spin %% Adding color to the base and implementing a softer twist base = zeros(180,360); baseR = georefcells([-90 90],[0 360],size(base)); copperColor = [0.62 0.38 0.24]; hs = geoshow(base, baseR,'FaceColor',copperColor); setm(gca,'Galtitude',0.025); axis vis3d spin
2.6
Matlab as a Graphing Tool Implementing the Mapping Toolbox
51
%% Show globe
clmo(hs) load mole topo = topo/(earthRadius('km')* 20); hs = meshm(topo, topolegend,size(topo), topo); demcmap(topo) set(gcf,'color','black'); axis off; spin camlight right lighting Gouraud; material ([.7, .9, .8])
The need to be able to visualize graphically in up to 3 dimensions various complicated problems developed in research and not having a tool to establish graphs to help us understand the proposed solution complicates the fact of being able to understand the immediate impact of this issue. The importance of implementing graphics has been supported from our basic training to more advanced stages of our research. This same importance is present in various areas of knowledge, such as biology, applied mathematics, and evolutionary computation. We can identify a direct application of graphs by associating them with work done in any area of science and technology, some mathematical analysis developed or simply in some presentation within our work environment. Understanding and displaying our solutions through graphs supports a simple and pleasant way to make known the results of our research. Therefore, it is recommended that any function resulting from an analysis found in relevant research be graphed to understand it better. Finally, it is recommended that once the analysis of a graph is finished, an exhaustive investigation is carried out to find different ways of graphing to see an innovative and dynamic visualization, which could present better parameters for understanding in case the techniques presented in this section do not meet the requirements of the project. We recommend that the reader use the most known and coined graphing techniques in the literature, such as those seen in the first sections of this chapter. In various investigations that may involve a global vision or a broader view of some important feature, it is possible to implement certain innovative techniques to ensure an understanding of what you want to explain. Through innovative designs, it is possible to arouse the user’s curiosity. Moreover, correct graphing allows us to visualize the problem and the proposed solution more clearly. Unfortunately, the recent pandemic has taught us that our area of analysis should not only focus on our country, city or colony, but we must expand the boundaries when addressing a problem. Therefore, the correct
52
2 Graphing with MATLAB
global visualization through MATLAB graphing is an important tool among the program’s offerings. When approaching a global problem, have a correctly sampled space graph. For this, we resort to not-so-common techniques such as those offered by MATLAB toolbox mapping. As we developed pages ago, displaying a moving globe makes it possible to attract the public’s attention to our experiments and consolidate, as described above, the knowledge related to our research. Another way of graphing our planet is through a world map. This time, to take it a little further, our priority will be to display a world map where you can identify each of the continents, as well as the most important cities of the most significant countries. However, the intention is to make the world map described above by adding an interactive component in which the user can select a part of the map with the mouse and the closest city to the selected point, and its location in coordinates will be displayed on the screen. To perform the above described, the reader will be guided step by step to develop and understand how to make an interactive world map and manipulate each section to adapt effectively to any field or area you want to apply. The world map will be displayed on the screen, and a series of red dots will be observed on it, indicating a city of interest, so that the user can intuitively move the mouse to that point to receive the information of the selected area, which will be graphed and displayed as Fig. 2.25. First, we will build the map with each region and terrain. For this, we will need to configure the axes of the map object and render the grid elevations; in addition to building the axes mentioned above, this is done with the following code block, which begins with
Fig. 2.25 Graph of a World Map
2.6
Matlab as a Graphing Tool Implementing the Mapping Toolbox
53
basic instructions for cleaning variables and output console. Then, the axesm function is implemented to indicate the projection implemented, which will be the Briesemeister, allowing us to observe a 2d figure with more emphasis on the continents than the oceans.
clc clear close all figure axesm bries text(.8, -1.8, 'Briesemeister projection') framem('FLineWidth',1)
After configuring the above, we can proceed to load the elevations to be displayed by loading the topo variable and implementing the geoshow command, which has as a parameter the display shape and texture of the map. Then, we will plot the most significant cities within the map, which can be identified with a red circular marker. For this, it is necessary to load and read a shapefile that contains the names and coordinates in latitude and longitude of the cities mentioned above. Implementing the shaperead command, as we have done previously, it is possible to obtain such information, which will be stored in multiple variables for proper implementation. The name of the cities will be held in “cities”, as well as the latitude and longitude in the variables “lats” and “lons”, respectively. Then, the geoshow command will be used again, adding as parameters the latitude and longitude of the cities and specifying the attributes of the markers. As the last parameter, one of the titles that will contain the graph is stipulated.
cities = shaperead('worldcities', 'UseGeoCoords', true);
lats = extractfield(cities,'Lat'); lons = extractfield(cities,'Lon'); geoshow(lats, lons,... 'DisplayType', 'point',... 'Marker', 'o',... 'MarkerEdgeColor', 'r',... 'MarkerFaceColor', 'r',... 'MarkerSize', 3) text(-2.8, -1.8,'Major cities of the world')
54
2 Graphing with MATLAB
With the above, we will only have a 2d map; however, as a last resource, we will add the interactive aspect where the user can select the cities or a region close to it. It will display the name of the same and its coordinates in latitude and longitude. For this, it is necessary to stipulate the use of the whole cycle, which will allow iterating infinitely until a stop criterion is found; this enables the user to identify a single city and discover the rest. It is important to note which instructions are used more simply than they are given that at the moment of developing something, it is possible to leave aside instructions that seem obvious. However, it is important to remember to be as explicit as possible when developing a program such as this one. Therefore, we stipulate that it is necessary to give a click with the mouse to a city or red point to obtain information about the same one. Additionally, it is specified that for the execution of the program, it is necessary to press the key entry of the keyboard.
The elevation 1-to-1 is loaded and displayed on the grid. load mole geoshow(topo, topolegend, 'DisplayType', 'texturemap') The terrain to be deployed is improved. A map color suitable for the elevation is obtained. demcmap(topo) Map brightness is increased brighten(.5) The coordinates of the coasts are loaded. load coastlines %We generalize coastlines to 0.25- degrees of tolerance [rlat, rlon] = reducem(coastlat, coastlon, 0.25); The coordinates are plotted in brown color. geoshow(rlat, rlon, 'Color', [.6 .5 .2], 'LineWidth', 1.5) disp('End of input.') end
Finally, we obtain the information of the selected city and display it to the user, or previously coded, obtaining the values of the variables chosen by implementing the find function. The geoshow function is executed again, as well as its parameters. However, this time, we stipulate the display of the name of the city by assigning to h2.string that attribute. We display the coordinates in latitude and longitude, assigning to h3.string the value of the necessary variables. It is appropriate to note that it is necessary to convert the numeric value of the variables city.lat and city.lon with the MATLAB native function num2string. With the above, it is possible to visualize an interactive world map, as shown in Fig. 2.26.
2.6
Matlab as a Graphing Tool Implementing the Mapping Toolbox
Fig. 2.26 Interactive world map, City of Guadalajara
runCitySelectionLoop = true; if(runCitySelectionLoop) h1 = text(-2.8, 1.9, 'Click on the red dots to get the city information. Press enter to exit'); h2 = text(-2.8, 1.7, ''); h3 = text(-2.8, 1.5, 'City coordinates.'); while true [selected_lat, selected_lon] = inputm(1); if isempty(selected_lat) break end d = distance(lats, lons, selected_lat, selected_lon); k = find(d == min(d(:))),1); city = cities(k); geoshow(city.Lat, city.Lon, ... 'DisplayType','point',... 'Marker', 'o', ... 'MarkerEdgeColor','k', ... 'MarkerFaceColor','y', ... 'MarkerSize', 3) h2.String = city.Name; h3.String = num2str([city.Lat, city.Lon],'%10.2f'); end
55
56
2 Graphing with MATLAB
References 1. McMahon, D. (2007). MATLAB demystified. New York, NY: McGraw-Hill. 2. Etter, D. M., Kuncicky, D. C., & Hull, D. W. (2002). Introduction to MATLAB. Hoboken, NJ, USA: Prentice Hall. 3. Menke, W., & Menke, J. (2016). Environmental data analysis with MATLAB. Academic Press. 4. Mapping toolbox. Mapping Toolbox Documentation - MathWorks Latin America (n.d.). Retrieved June 8, 2022, from https://la.mathworks.com/help/map/index.html.
3
Linear Algebra
Abstract
The study of linear algebra is fundamental for understanding and working effectively with numerical methods in MATLAB® . This branch of mathematics forms the basis of MATLAB® ’s usage due to its powerful matrix and vector operations capabilities, enabling users to leverage the software’s features fully. This chapter will delve into the essentials of linear algebra, including solving linear equations and manipulating matrices and vectors. We will explore the proper representation of linear equations and familiarize ourselves with the basic operations performed using matrix and vector notation. Additionally, we will review MATLAB® syntax for working with linear equations in matrix form. We will also address challenging and unsolvable problems and supplementary topics that enhance the practical application of algebraic concepts. In Sect. 3.1, a short introduction to the chapter is given. Section 3.2 describes the essential elements of matrices and vectors. Section 3.3 presents the implementation of different operations of matrices and vectors. Additionally, Sect. 3.4 reviews the most important features of systems of linear equations. Section 3.5 gives an overview of the determinant of a square matrix, and in Sect. 3.6, ill-conditioned problems are addressed. In Sects. 3.7 and 3.8, the implementation of Gauss elimination and Gauss–Jordan elimination are reviewed, respectively. Section 3.9 LU decomposition is applied, and finally, in Sect. 3.10, the eigenvalues of matrices are discussed.
3.1
Introduction
One of the most fundamental tools for studying numerical methods and the main basis for working in MATLAB® is the study of linear algebra. The main basis for working in MATLAB® is the study of linear algebra, given its capabilities for the operation of
© The Author(s), under exclusive license to Springer Nature Switzerland AG 2024 E. Cuevas et al., Computational Methods with MATLAB® , Synthesis Lectures on Engineering, Science, and Technology, https://doi.org/10.1007/978-3-031-40478-8_3
57
58
3 Linear Algebra
matrices and vectors, which means that the knowledge of this tool allows us to make greater use of the study software. In this chapter, we will study the fundamentals of linear algebra, linear equation solving, and the resolution of linear equations. We will examine the correct way to express linear equations and the basic operations in matrix and vector notation. The syntax of MATLAB® in linear equations with matrix notation will be reviewed. The difficult and unsolvable problems will be analyzed, as well as additional topics that will help to make a greater application of algebra [1, 2].
3.2
Matrices and Vectors
Since in MATLAB® , the terms array and matrix are synonymous. It is necessary to clarify whether an array is used as a mathematical element or a simple variable. In mathematical notation, matrices are usually enclosed in square brackets and follow certain rules. This subtopic will review these rules and discuss matrices and vectors in their strict mathematical sense. In mathematics, a matrix is a rectangular array of numbers enclosed in square brackets and can be represented as follows: ⎡ ⎢ ⎢ ⎢ ⎢ ⎣
x1,1 x1,2 . . . x1,n x2,1 x2,2 . . . x2,n .. .. . .. . .. . . xm,1 xm,2 . . . xm,n
⎤ ⎥ ⎥ ⎥ ⎥ ⎦
(3.1)
This array is a matrix of dimension m × n. It can be observed how the subscripts m change in the vertical direction and the subscripts n change in the horizontal direction. The matrices are represented by a symbol, for example: ⎡ ⎢ ⎢ M =⎢ ⎢ ⎣
x1,1 x1,2 . . . x1,n x2,1 x2,2 . . . x2,n . .. .. .. . .. . . xm,1 xm,2 . . . xm,n
⎤ ⎥ ⎥ ⎥ ⎥ ⎦
(3.2)
Once the matrix M has been determined, it can be represented in a mathematical equation in terms of M without having to write the whole matrix, abbreviated as follows: [ ] M = xi, j
(3.3)
On the other hand, a vector is a special case of a matrix with dimensions either m × 1 or 1 × n, thus having a column vector or row vector, respectively, and can be represented as follows:
3.2
Matrices and Vectors
59
⎡ ⎢ ⎢ vc = ⎢ ⎢ ⎣
x1,1 x2,1 .. . xm,1
⎤ ⎥ ⎥ ⎥ ⎥ ⎦
vr = [x1,1 , x1,2 , . . . , x1,n ]
(3.4)
Since, in both cases, one of the indices remains constant, it is omitted from the notation, leaving the vectors represented in (3.4) as follows: ⎡ ⎤ x1 ⎢ ⎥ ⎢ x2 ⎥ ⎥ vc = ⎢ ⎢ .. ⎥ ⎣ . ⎦ xm vr = [x1 , x2 , . . . , xn ]
(3.5)
In MATLAB® , it is possible to define vectors and matrices by separating column values with spaces “ ” or commas “,” and separating rows using a semicolon “;”. For example:
c"?"]3"4="6"5="2"4_
Result:
c"? 3"4 6"5 2"4
The same notation is used for the use of vectors. Other special cases of matrices are: Scalar matrix: Matrix of dimension 1 × 1 being M = [x]. Square matrix: is a matrix of dimensions m = n.
60
3 Linear Algebra
Identity Matrix: is that square matrix for which its elements in the main diagonal have the value of 1 and the rest of the elements are 0. An example of the case of a matrix of 3 × 3 is as follows: ⎡ ⎤ 100 ⎢ ⎥ (3.6) I = ⎣0 1 0⎦ 001 The command in MATLAB® to define an identity matrix is I = eye(n), where I is assigned an identity matrix of dimensions n × n. Null Matrix: a matrix in which all its elements have zero value. In MATLAB® , null matrices are defined as N = zeros(m,n), resulting in a null matrix of dimensions m × n in the case of using only one argument as N = zeros(n), returning a null matrix of size n × n.
3.3
Matrix and Vector Operations
In this section, we will study the basic operations with matrices and how to perform them in MATLAB® [3]. Transpose of a Matrix: The transpose of a matrix is obtained by changing the rows of the matrix by columns of the matrix. ⎡ ⎤ x1,1 . . . x1,n ⎢ . . . ⎥ ⎥ para M = ⎢ ⎣ .. . . .. ⎦ xm,1 · · · xm,n ⎡ ⎤ x1,1 . . . xm,1 ⎢ . . .. ⎥ ⎥ . . MT = ⎢ (3.7) . . ⎦ . ⎣ x1,n · · · xn,m For example: [ para M = [ M = T
] 38 46
]
34 86
para M = [ 7 2 ]
o
3.3
Matrix and Vector Operations
61
[ ] 7 MT = 2
(3.8)
In MATLAB® , this operation is performed with the apostrophe operator being, for example:
O"?"]9.4_= OV"?"O)=
Assigning to MT the transpose of the matrix M results in the second example shown in (3.8). Addition and Subtraction of Matrices: It is possible to add and subtract matrices or vectors as long as both have the same dimension. Having for: [ ] A = ai, j and B = [bi j ]
(3.9)
where A and B are matrices of the same dimension. We define addition and subtraction as: C = A±B
(3.10)
ci j = ai j ± bi j
(3.11)
where C = [ci j ] for:
In MATLAB® , it is only necessary to define two matrices of equal dimensions and use the addition “+” or subtraction “-” operator depending on the case. Multiplication of Matrices: Having a matrix of dimensions of A of dimensions m 1 × n 1 and a matrix of B dimension matrix m 2 × n 2 these can be multiplied only if m 1 = n 2 . Otherwise, the matrices will be incompatible under the multiplication criterion. Then, since matrices A = [ai j ] and B[bi j ] satisfy the above condition, the product of the two matrices is given by: C = AB
(3.12)
ci j = ai ,1 b1, j + ai,2 b2, j + · · · + ai ,n bn, j
(3.13)
For C = [ci j ] where:
62
3 Linear Algebra
In MATLAB® , it is only necessary to define the matrices and use the multiplication operator “*” between them. The system will throw an error if the compatibility criterion is not met under multiplication. The Inverse of a Matrix or Inverse Matrix: The inverse of a matrix M written as M −1 is that matrix such that when calculating: M M −1 = I
(3.14)
where I is the identity matrix mentioned previously in Sect. 3.1. It is worth noting that to obtain the inverse of a matrix, it must be a square matrix; that is, its dimensions are m × m. In MATLAB® , the inverse of a matrix can be calculated using the command “inv(M)”, where M is the matrix whose inverse is to be known.
3.4
Systems of Linear Equations
In linear algebra, a system of linear equations is a set of linear equations defined on a commutative ring. Consider a set of m equations with n unknowns given by: a1,1 x1 + a1,2 x2 + · · · + a1,n xn = s1 a2,1 x1 + a2,2 x2 + · · · + a2n xn = s2 .. . am,1 x1 + am,2 x2 + · · · + am,n xn = sm
(3.15)
where ai , j are known coefficients, xi are the unknowns of the equation and si are nonhomogeneous terms. The system can be expressed in matrix notation as follows: First, the system of linear equations is compacted as follows: Ax = s where A is the known coefficient matrix defined as: ⎡ ⎤ a1,1 . . . a1,n ⎢ . . .. ⎥ ⎥ . . A=⎢ . . ⎦ . ⎣ am,1 · · · am,n x is the column vector of unknowns given by:
(3.16)
(3.17)
3.5
Determinant of a Square Matrix
63
⎡
⎤ x1 ⎢ . ⎥ ⎥ x =⎢ ⎣ .. ⎦ xn s is the column vector of nonhomogeneous terms: ⎡ ⎤ s1 ⎢ . ⎥ ⎥ s=⎢ ⎣ .. ⎦ sm
(3.18)
(3.19)
Once the system is compacted and cleared for x, it follows that the solution to the system of equations is given by: x = A−1 s
(3.20)
This can be achieved in MATLAB® with the command “x = inv(A)* s” by storing in “x” the vector of solutions to the system of equations y, where “A” and “s” are the coefficient matrix and the vector of nonhomogeneous terms, respectively. Unfortunately, systems of linear equations do not always have a numerical solution because the solution of the system is geometrically located at the point of intersection of the straight lines defined by the linear equations of the system. This issue leads us to the following cases: Illustration 3.1 shows the different solution scenarios for a system of linear equations: A.—The lines defined in the system have only one intersection and therefore have a unique solution. B.—The lines defined in the system are superimposed one over the other, causing an infinite number of solutions. This scenario makes it impossible to give a numerical answer. C.—There are two parallel lines in this case, so the system has no intersection. Therefore, it does not have a solution or three independent equations for two unknowns, which causes the system to never be satisfied simultaneously, so it does not have a solution either.
3.5
Determinant of a Square Matrix
One of the quantities of greatest interest is related to the square matrices since it allows us to know the unique solution in the systems of linear equations. When the value of the determinant of a matrix is equal to zero, the system of equations that conform to it does not have a unique solution. In addition to playing an important role in calculating these eigenvalues is the determinant.
64
3 Linear Algebra
Illustration 3.1 Possible solutions for a system of linear equations
The determinant of a matrix is denoted by |M| depending on the dimension of the matrix, and it has different ways of being calculated; in the case of matrices of 2 × 2, it can be calculated as: |[ ]| | | | x1,1 x1,2 | |M| = | (3.21) | = x1,1 · x2,2 − x1,2 · x1,2 | x2,1 x2,2 | For a matrix of 3 × 3:
3.6
Ill-Conditioned Problems
65
|⎡ ⎤| | | x x x | 1,1 1,2 1,3 | |⎢ ⎥| |M| = |⎣ x2,1 x2,2 x2,3 ⎦| | | | x3,1 x3,2 x3,3 | = x1,1 · x2,2 · x3,3 + x1,3 · x2,1 · x3,2 + x1,2 · x2,3 · x3,1 − x1,3 · x2,2 · x3,1 − x1,2 · x2,1 · x3,3 − x1,1 · x2,3 · x3,2 For higher dimensional matrices, the determinant can be calculated as follows: Σ |M| = (±)xi ,1 · x j,2 · xk,3 . . . kr ,n
(3.22)
(3.23)
i , j,k,...r
where the summation implies all possible permutations of the first subscript of x, y (±) is “+” for the case of an even permutation and “−” for the case of an odd permutation. To calculate the determinant of a matrix in MATLAB® , it is only necessary to use the command “det(m)”, where “m” is the square matrix from which we want to obtain the determinant.
3.6
Ill-Conditioned Problems
Several problems involving many linear equations that are solved tend to be inaccurate values because serious mistakes occur when implementing the rounding technique. When this happens, it is called an ill-conditioned problem. The small errors that arise when solving linear equations by rounding can lead to erroneous results when solving an illconditioned problem. 0.12032x + 0.98755y = 2.00555
(3.24)
0.12065x + 0.98775y = 2.01045
(3.25)
Rounding errors are mostly seen in the example illustrated in Eqs. 3.1 and 3.2. When analyzing the instance, it is evident that the two equations are very close. The solution is found and denoted by x1 = 14.7403 y y1 = 0.23942. 0.001 is artificially increased in Eq. 3.2 to make the coefficient error even more evident in its nonhomogeneous term. Therefore, the resulting system is the following: 0.12032x + 0.98755y = 2.00555
(3.26)
0.12065x + 0.98775y = 2.01145
(3.27)
The solution to the above system will be identified as x2 = 17.9756 and y2 = −0.15928. Analyzing the above, it is possible to understand that the differences between
66
3 Linear Algebra
the first solution set (x1 , y1 ) and the second solution set (x2 , y2 ) represent a significant disparity. This disparity is more important when considering the small increase applied and the alteration obtained. Using such changes at the time of rounding can cause similar phenomena when solving the system of equations. The previously mentioned effect becomes increasingly significant as the number of equations increases. In the following sections, we will analyze two techniques with which we will be able to validate whether a specific matrix is ill-conditioned or not. The first technique consists of implementing the condition number; however, it is necessary to remember certain fundamental aspects, such as rule 2 of a specific matrix, before applying this technique. This rule is defined below: ┌⎛ ⎞ ┃ ┃ Σ ┃ ||A|| = √⎝ |Ai , j |2 ⎠ (3.28) i, j
The value of the condition of matrix A is identified by Cond(A) and is defined by Eq. 3.29, and the value of the condition always satisfies Cond(A) > 1. The value of the condition usually increases concerning whether the matrix is ill-conditioned, but it should be noted that this value does not measure the error. | | (3.29) Cond(A) = ||A|| · || A−1 || In MATLAB, it is possible to obtain the condition value by applying the line of code “cond(A)”, using the above coding to solve the problem of Eq. 3.1. We have “cond ([0.12065, 0.98775; 0.12032, 0.98755])”. To evaluate a poorly conditioned problem more accurately, it is also important to have a higher degree of accuracy in the calculations. The inverse and the determinant of an ill-conditioned matrix are not exact. It is possible to evaluate if the mentioned errors exist by validating certain points, such as validating that the determinant of A multiplied by the determinant of the inverse of A is different from one, validating that the determinant of A multiplied by the determinant of the inverse of ) ( A is different from one: det(A)det A−1 / = 1, validating that the inverse of the inverse −1
of A is different from A: (A−1 ) / = A, validating that multiplying A times the inverse of A is different from the identity matrix: A A−1 / = I (A), validating that multiplying the inverse of A by the inverse of the inverse of A is significantly different from the identity ( )−1 matrix of A, even more than the above validation: A−1 A−1 . Exercise A Commonly, Hilbert matrices have the problem that they are ill conditioned. Hilbert matrices can be defined as A = [ai, j ], where ai, j =
1 i + j −1
(3.30)
3.7
Gaussian Elimination
67
With the above, it is necessary to obtain the condition value and the multiplication of ) ( the determinant of A by the determinant of the inverse of A: det(A)det A−1 for Hilbert matrices from 6 by 6 to 11 by 11. The solution to the above exercise can be obtained with the following coding:
engct"cnn hqt"p?8 |a ' i,2 , |, If the above is not met, the equation permutes the pivot to be the one with the highest value before starting the elimination, which is implemented at each pivot until the forward elimination process is completed. Exercise B Solve the equations by implementing double precision based on the following system of equations, composed of four equations and unknowns. It is prudent to note that the exact answer is unity by applying double precision and the pivoting technique since each nonhomogeneous term equals the sum of the coefficients in the same row. 1.334 × 10 − 4 1.777 9.188 1.002 × 10 + 2
4.123 × 10 + 1 2.367 × 10 − 5 0 1.4442 × 10 + 4
7.912 × 10 + 2 2.070 × 10 + 1 −1.015 × 10 + 1 −7.014 × 10 + 2
−1.544 × 10 + 3 −9.035 × 10 + 1 1.988 × 10 − 4 5.321
Applying the following coding
engct"cnn C?]305562g/26"603452g-23"90;342g-24"/ 307662g-25= 309992g-22"405892g/27"402922g-23"/ ;02572g-23= ;03::2g-22"2"/302372g-23"30;::2g/26= 302242g-24"306664g-6"/902362g-24" 705432g-22_= {"?uwo*C)+)= hqtocv"nqpi"g
−711.5698662 −67.87297633 −0.961801200 13824.12100
70
3 Linear Algebra
We obtain the following result. x= 9.999999999999570e − 01 1.000000000000000e + 00 9.999999999999980e − 01 9.999999999999991e − 01
3.8
Gauss–Jordan Elimination
The Gauss–Jordan elimination methodology is a variant of the Gaussian elimination technique where the numbers above and below a pivot are eliminated without differentiating forward elimination in contrast to backward substitution. However, it is necessary to add the pivoting technique. Exercise C Solve the following equation by Gauss–Jordan elimination defining the augmented matrix where the first three columns are the coefficients, and the last one is the right member. This augmented matrix is described below:
C?"]/2026"2026"2034"5= 2078"/3078"2054"3= /2046"3046"/24:"2_=
Implementing the first pivot (exchange of rows 1 and 2) in addition to normalizing the first row by dividing it by the pivot, we then proceed to eliminate all elements below the pivot by applying additions or subtractions of a multiple of the first row with the second and third rows. We obtain the second pivot by dividing the row by the element’s value [2, 2] to eliminate the top and bottom elements by applying the same methodology. For the third pivot, we perform the division and eliminate the top elements obtaining the solution set. The following code performs the process described above:
3.8
Gauss–Jordan Elimination
71
engct"cnn C?]/2026"2026"2034"5= 2078"/3078"2054"3= /2046"3046"/204:"2_= z?]2.2.2_)= hktuv"rkxqv"ku"korngogpvgf v?C*4.