1.2: Essentials
- Page ID
- 9460
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)Learning a new skill, especially a computer program in this case, can be overwhelming. However, if we build on what we already know, the process can be handled rather effectively. In the preceding chapter we learned about MATLAB Graphical User Interface (GUI) and how to get help. Knowing the GUI, we will use basic math skills in MATLAB to solve linear equations and find roots of polynomials in this chapter.
Basic Computation
Mathematical Operators
The evaluation of expressions is accomplished with arithmetic operators as we use them in scientific calculators. Note the addtional operators shown in the table below:
Operator | Name | Description |
+ | Plus | Addition |
- | Minus | Subtraction |
* | Asterisk | Multiplication |
/ | Forward Slash | Division |
\ | Back Slash | Left Matrix Division |
^ | Caret | Power |
.* | Dot Asterisk | Array multiplication (element-wise) |
./ | Dot Slash | Right array divide (element-wise) |
.\ | Dot Back Slash | Left array divide (element-wise) |
.^ | Dot Caret | Array power (element-wise) |
Operators
The backslash operator is used to solve linear systems of equations, see Section.
important:
Matrix is a rectangular array of numbers and formed by rows and columns. For example
\(A=\left( \begin{array}{cccc}{1} & {2} & {3} & {4} \\ {5} & {6} & {7} & {8} \\ {9} & {10} & {11} & {12} \\ {13} & {14} & {15} & {16}\end{array}\right)\). In this example A consists of 4 rows and 4 columns and therefore is a 4x4 matrix. (see Wikipedia).
Important:
Row vector is a special matrix that contains only one row. In other words, a row vector is a 1xn matrix where n is the number of elements in the row vector. \(B=\left( \begin{array}{lllll}{1} & {2} & {3} & {4} & {5}\end{array}\right)\)
important:
Column vector is also a special matrix. As the term implies, it contains only one column. A column vector is an nx1 matrix where n is the number of elements in the column vector. \(C=\left( \begin{array}{l}{1} \\ {2} \\ {3} \\ {4} \\ {5}\end{array}\right)\)
Array operations refer to element-wise calculations on the arrays, for example if x is an a by b matrix and y is a c by d matrix then x.*y can be performed only if a=c and b=d. Consider the following example, x consists of 2 rows and 3 columns and therefore it is a 2x3 matrix. Likewise, y has 2 rows and 3 columns and an array operation is possible. \(x=\left( \begin{array}{lll}{1} & {2} & {3} \\ {4} & {5} & {6}\end{array}\right)\) and \(y=\left( \begin{array}{lll}{10} & {20} & {30} \\ {40} & {50} & {60}\end{array}\right)\) then x. \(* y=\left( \begin{array}{ccc}{10} & {40} & {90} \\ {160} & {250} & {360}\end{array}\right)\)
The following figure illustrates a typical calculation in the Command Window.
\(\PageIndex{1}\). Basic arithmetic in the command window.
Operator Precedence
MATLAB allows us to build mathematical expressions with any combination of arithmetic operators. The order of operations are set by precedence levels in which MATLAB evaluates an expression from left to right. The precedence rules for MATLAB operators are shown in the list below from the highest precedence level to the lowest.
- Parentheses ()
- Power (^)
- Multiplication (*), right division (/), left division (\)
- Addition (+), subtraction (-)
Mathematical Functions
MATLAB has all of the usual mathematical functions found on a scientific calculator including square root, logarithm, and sine.
important:
Typing
pi
returns the number 3.1416. To find the sine of pi, type in
sin(pi)
and press enter.
important:
The arguments in trigonometric functions are in radians. Multiply degrees by pi/180 to get radians. For example, to calculate sin(90), type in
sin(90*pi/180)
warning:
In MATLAB
log
returns the natural logarithm of the value. To find the ln of 10, type in log(10) and press enter, (ans = 2.3026).
warning:
MATLAB accepts
log10for common (base 10) logarithm. To find the log of 10, type in log10(10) and press enter, (ans = 1).
Practice the following examples to familiarize yourself with the common mathematical functions. Be sure to read the relevant help
and doc
pages for functions that are not self explanatory.
Calculate the following quantities:
1. \(\frac{2^{3}}{3^{2}-1}\)
2. \(5^{0.5}-1\)
3. \(\frac{\pi}{4} d^{2}\) for \(d=2\)
MATLAB inputs and outputs are as follows:
1. \(\frac{2^{3}}{3^{2}-1}\) is entered by typing 2^3/(3^2-1)
(ans = 1)
2. \(5^{0.5}-1\) is entered by typing sqrt(5)-1
(ans = 1.2361)
3. \(\frac{\pi}{4} d^{2}\) for \(d=2\) is entered by typing pi/4*2^2
(ans = 3.1416)
Calculate the following exponential and logarithmic quantities:
1. \(e^{2}\)
2. \(\ln \left(5^{10}\right)\)
3. \(\log 10^{5}\)
MATLAB inputs and outputs are as follows:
exp(2)
(ans = 7.3891)log((5^10))
(ans = 16.0944)log10(10^5)
(ans = 5)
Calculate the following trigonometric quantities:
1. \(\cos \left(\frac{\pi}{6}\right)\)
2. \(\tan (45)\)
3. \(\log 10^{5}\)
MATLAB inputs and outputs are as follows:
cos(pi/6)
(ans = 0.8660)tan(45*pi/180)
(ans = 1.0000)sin(pi)+cos(45*pi/180)
(ans = 0.7071)
The
format
Function
The format
function is used to control how the numeric values are displayed in the Command Window. The short
format is set by default and the numerical results are displayed with 4 digits after the decimal point (see the examples above). The long
format produces 15 digits after the decimal point.
Calculate \(\theta=\tan \left(\frac{\pi}{3}\right)\) and display results in short
and long
formats.
The short
format is set by default:
>> theta=tan(pi/3) theta = 1.7321 >>
And the long
format is turned on by typing format long
:
>> theta=tan(pi/3) theta = 1.7321 >> format long >> theta theta = 1.732050807568877
Variables
In MATLAB, a named value is called a variable. MATLAB comes with several predefined variables. For example, the name pi refers to the mathematical quantity π, which is approximately pi ans = 3.1416
warning:
MATLAB is case-sensitive, which means it distinguishes between upper- and lowercase letters (e.g. data, DATA and DaTa are three different variables). Command and function names are also case-sensitive. Please note that when you use the command-line help, function names are given in upper-case letters (e.g., CLEAR) only to emphasize them. Do not use upper-case letters when running functions and commands.
Declaring Variables
Variables in MATLAB are generally represented as matrix quantities. Scalars and vectors are special cases of matrices having size 1x1 (scalar), 1xn (row vector) or nx1 (column vector).
Declaration of a Scalar
The term scalar as used in linear algebra refers to a real number. Assignment of scalars in MATLAB is easy, type in the variable name followed by = symbol and a number:
a = 1
\(\PageIndex{2}\). Assignment of a scalar quantity.
Declaration of a Row Vector
Elements of a row vector are separated with blanks or commas.
Let's type the following at the command prompt:
b = [1 2 3 4 5]
\(\PageIndex{3}\). Assignment of a row vector quantity.
We can also use the New Variable button to assign a row vector. In the tool strip, select Home > New Variable. This action will create a variable called unnamed which is displayed in the workspace. By clicking on the title unnamed, we can rename it to something more descriptive. By double-clicking on the variable, we can open the Variable Editor and type in the values into spreadsheet looking table.
\(\PageIndex{4}\). Using the New Variable button in the tool strip.
\(\PageIndex{5}\). Assignment of a row vector by using the Variable Editor.
Declaration of a Column Vector
Elements of a column vector is ended by a semicolon:
c = [1;2;3;4;5;]
\(\PageIndex{6}\). Assignment of a column vector quantity.
Or by transposing a row vector with the ' operator:
c = [1 2 3 4 5]'
\(\PageIndex{7}\). Assignment of a column vector quantity by transposing a row vector with the ' operator.
Or by using the Variable Editor:
\(\PageIndex{8}\). Assignment of a column vector quantity by using the Variable Editor.
Declaration of a Matrix
Matrices are typed in rows first and separated by semicolons to create columns. Consider the examples below:
Let us type in a 2x5 matrix:
d = [2 4 6 8 10; 1 3 5 7 9]
\(\PageIndex{9}\). Assignment of a 2x5 matrix.
\(\PageIndex{10}\). Assignment of a matrix by using the Variable Editor.
This example is a 5x2 matrix:
\(\PageIndex{11}\). Assignment of a 5x2 matrix.
Linear Equations
Systems of linear equations are very important in engineering studies. In the course of solving a problem, we often reduce the problem to simultaneous equations from which the results are obtained. As you learned earlier, MATLAB stands for Matrix Laboratory and has features to handle matrices. Using the coefficients of simultaneous linear equations, a matrix can be formed to solve a set of simultaneous equations.
Let's solve the following simultaneous equations:
\(x+y=1\)
\(2 x-5 y=9\)
First, we will create a matrix for the left-hand side of the equation using the coefficients, namely 1 and 1 for the first and 2 and -5 for the second. The matrix looks like this:
\(\left( \begin{array}{cc}{1} & {1} \\ {2} & {-5}\end{array}\right)\)
The above matrix can be entered in the command window by typing A=[1 1; 2 -5]
.
Second, we create a column vector to represent the right-hand side of the equation as follows:
\(\left( \begin{array}{l}{1} \\ {9}\end{array}\right)\)
The above column vector can be entered in the command window by typing B= [1;9]
.
To solve the simultaneous equation, we will use the left division operator and issue the following command: C=A\B
. These three steps are illustrated below:
>> A=[1 1; 2 -5] A = 1 1 2 -5 >> B= [1;9] B = 1 9 >> C=AB C = 2 -1 >>
The result C
indicating 2 and 1 are the values for x
and y
, respectively.
Polynomials
In the preceding section, we briefly learned about how to use MATLAB to solve linear equations. Equally important in engineering problem solving is the application of polynomials. Polynomials are functions that are built by simply adding together (or subtracting) some power functions. (see Wikipedia).
\(a x^{2}+b x+c=0\)
\(\mathrm{f}(\mathrm{x})=a x^{2}+b x+c\)
The coeffcients of a polynominal are entered as a row vector beginning with the highest power and including the ones that are equal to 0.
Create a row vector for the following function: \(y=2 x^{4}+3 x^{3}+5 x^{2}+x+10\)
Notice that in this example we have 5 terms in the function and therefore the row vector will contain 5 elements. p=[2 3 5 1 10]
Create a row vector for the following function: \(y=3 x^{4}+4 x^{2}-5\)
In this example, coefficients for the terms involving power of 3 and 1 are 0. The row vector still contains 5 elements as in the previous example but this time we will enter two zeros for the coefficients with power of 3 and 1: p=[3 0 4 0 -5]
.
The
polyval
Function
We can evaluate a polynomial p
for a given value of x
using the syntax polyval(p,x)
where p contains the coefficients of polynomial and x is the given number.
Evaluate f(x) at 5.
\(f(x)=3 x^{2}+2 x+1\)
The row vector representing f(x) above is p=[3 2 1]
. To evaluate f(x) at 5, we type in: polyval(p,5)
. The following shows the Command Window output:
>> p=[3 2 1] p = 3 2 1 >> polyval(p,5) ans = 86 >>
The
roots
Function
Consider the following equation:
\(a x^{2}+b x+c=0\)
Probably you have solved this type of equations numerous times. In MATLAB, we can use the roots
function to find the roots very easily.
Find the roots for the following:
\(0.6 x^{2}+0.3 x-0.9=0\)
To find the roots, first we enter the coefficients of polynomial in to a row vector p with p=[0.6 0.3 -0.9]
and issue the r=roots(p)
command. The following shows the command window output:
>> p=[0.6 0.3 -0.9] p = 0.6000 0.3000 -0.9000 >> r=roots(p) r = -1.5000 1.0000 >>
Splitting a Statement
You will soon find out that typing long statements in the Command Window or in the the Text Editor makes it very hard to read and maintain your code. To split a long statement over multiple lines simply enter three periods "..." at the end of the line and carry on with your statement on the next line.
The following command window output illustrates the use of three periods:
>> sin(pi)+cos(45*pi/180)-sin(pi/2)+cos(45*pi/180)+tan(pi/3) ans = 2.1463 >> sin(pi)+cos(45*pi/180)-sin(pi/2)... +cos(45*pi/180)+tan(pi/3) ans = 2.1463 >>
Comments
Comments are used to make scripts more "readable". The percent symbol % separates the comments from the code. Examine the following examples:
The long statements are split to make it easier to read. However, despite the use of descriptive variable names, it is hard to understand what this script does, see the following Command Window output:
t_water=80; t_outside=15; inner_dia=0.05; thickness=0.006; Lambda_steel=48; AlfaInside=2800; AlfaOutside=17; thickness_insulation=0.012; Lambda_insulation=0.03; r_i=inner_dia/2 r_o=r_i+thickness r_i_insulation=r_o r_o_insulation=r_i_insulation+thickness_insulation AreaInside=2*pi*r_i AreaOutside=2*pi*r_o AreaOutside_insulated=2*pi*r_o_insulation AreaM_pipe=(2*pi*(r_o-r_i))/log(r_o/r_i) AreaM_insulation=(2*pi*(r_o_insulation-r_i_insulation)) ... /log(r_o_insulation/r_i_insulation) TotalResistance=(1/(AlfaInside*AreaInside))+ ... (thickness/(Lambda_steel*AreaM_pipe))+(1/(AlfaOutside*AreaOutside)) TotalResistance_insulated=(1/(AlfaInside*AreaInside))+ ... (thickness/(Lambda_steel*AreaM_pipe))+(thickness_insulation ... /(Lambda_insulation*AreaM_insulation))+(1/(AlfaOutside*AreaOutside_insulated)) Q_dot=(t_water-t_outside)/(TotalResistance*1000) Q_dot_insulated=(t_water-t_outside)/(TotalResistance_insulated*1000) PercentageReducttion=((Q_dot-Q_dot_insulated)/Q_dot)*100
The following is an edited version of the above including numerous comments:
% Problem 16.06 % Problem Statement % Calculate the percentage reduction in heat loss when a layer of hair felt % is wrapped around the outside surface (see problem 16.05) format short % Input Values t_water=80; % Water temperature [C] t_outside=15; % Atmospheric temperature [C] inner_dia=0.05; % Inner diameter [m] thickness=0.006; % [m] Lambda_steel=48; % Thermal conductivity of steel [W/mK] AlfaInside=2800; % Heat transfer coefficient of inside [W/m2K] AlfaOutside=17; % Heat transfer coefficient of outside [W/m2K] % Neglect radiation % Additional layer thickness_insulation=0.012; % [m] Lambda_insulation=0.03; % Thermal conductivity of insulation [W/mK] % Output Values % Q_dot=(t_water-t_outside)/TotalResistance % TotalResistance=(1/(AlfaInside*AreaInside))+(thickness/(Lambda_steel*AreaM))+ ... (1/(AlfaOutside*AreaOutside) % Calculating the unknown terms r_i=inner_dia/2 % Inner radius of pipe [m] r_o=r_i+thickness % Outer radius of pipe [m] r_i_insulation=r_o % Inner radius of insulation [m] r_o_insulation=r_i_insulation+thickness_insulation % Outer radius of pipe [m] AreaInside=2*pi*r_i AreaOutside=2*pi*r_o AreaOutside_insulated=2*pi*r_o_insulation AreaM_pipe=(2*pi*(r_o-r_i))/log(r_o/r_i) % Logarithmic mean area for pipe AreaM_insulation=(2*pi*(r_o_insulation-r_i_insulation)) ... /log(r_o_insulation/r_i_insulation) % Logarithmic mean area for insulation TotalResistance=(1/(AlfaInside*AreaInside))+(thickness/ ... (Lambda_steel*AreaM_pipe))+(1/(AlfaOutside*AreaOutside)) TotalResistance_insulated=(1/(AlfaInside*AreaInside))+(thickness/ ... (Lambda_steel*AreaM_pipe))+(thickness_insulation/(Lambda_insulation*AreaM_insulation)) ... +(1/(AlfaOutside*AreaOutside_insulated)) Q_dot=(t_water-t_outside)/(TotalResistance*1000) % converting into kW Q_dot_insulated=(t_water-t_outside)/(TotalResistance_insulated*1000) % converting into kW PercentageReducttion=((Q_dot-Q_dot_insulated)/Q_dot)*100
Basic Operations
Command | Meaning |
sum | Sum of array elements |
prod | Product of array elements |
sqrt | Square root |
log10 | Common logarithm (base 10) |
log | Natural logarithm |
max | Maximum elements of array |
min | Minimum elements of array |
mean | Average or mean value of arrays |
std | Standard deviation |
Special Characters
Character | Meaning |
= | Assignment |
( ) | Prioritize operations |
[ ] | Construct array |
: | Specify range of array elements |
, | Row element separator in an array |
; | Column element separator in an array |
... | Continue statement to next line |
. | Decimal point, or structure field separator |
% | Insert comment line into code |
Special Characters
Summary of Key Points
- MATLAB has the common functions found on a scientific calculator and can be operated in a similar way,
- MATLAB can store values in variables. Variables are case sensitive and some variables are reserved by MATLAB (e.g.
pi
stores 3.1416), - Variable Editor can be used to enter or manipulate matrices,
- The coefficients of simultaneous linear equations and polynomials are used to form a row vector. MATLAB then can be used to solve the equations,
- The
format
function is used to control the number of digits displayed, - Three periods "..." at the end of the line is used to split a long statement over multiple lines,
- The percent symbol % separates the comments from the code, anything following % symbol is ignored by MATLAB.