Skip to content Skip to navigation Skip to collection information

OpenStax-CNX

You are here: Home » Content » A Brief Introduction to Engineering Computation with MATLAB » Essentials

Navigation

Recently Viewed

This feature requires Javascript to be enabled.
 

Essentials

Module by: Serhat Beyenir. E-mail the author

Summary: Essential skills to use MATLAB effectively.

MATLAB Essentials

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:

Table 1: Operators
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)

Note:

The backslash operator is used to solve linear systems of equations, see Section 12.

Important:

Matrix is a rectangular array of numbers and formed by rows and columns. For example A=( 1234 5678 9101112 13141516 ) A 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 . 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=( 12345 ) B 1 2 3 4 5

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=( 1 2 3 4 5 ) C 1 2 3 4 5

Note:

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=( 123 456 ) x 1 2 3 4 5 6 and y=( 102030 405060 ) y 10 20 30 40 50 60 then x.*y=( 104090 160250360 ) x.*y 10 40 90 160 250 360

Example 1

The following figure illustrates a typical calculation in the Command Window.

Figure 1: Basic arithmetic in the command window.
Example

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.

  1. Parentheses ()
  2. Power (^)
  3. Multiplication (*), right division (/), left division (\)
  4. 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 log10 for 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.

Example 2

Calculate the following quantities:

  1. 23321 2 3 3 2 1 ,
  2. 50.51 5 0.5 1
  3. π4d2 4 d 2 for d=2

MATLAB inputs and outputs are as follows:

  1. 23321 2 3 3 2 1 is entered by typing 2^3/(3^2-1) (ans = 1)
  2. 50.51 5 0.5 1 is entered by typing sqrt(5)-1 (ans = 1.2361)
  3. π4d2 4 d 2 for d=2 is entered by typing pi/4*2^2 (ans = 3.1416)

Example 3

Calculate the following exponential and logarithmic quantities:

  1. e2 2
  2. ln510 5 10
  3. log105 10 5

MATLAB inputs and outputs are as follows:

  1. exp(2) (ans = 7.3891)
  2. log((5^10)) (ans = 16.0944)
  3. log10(10^5) (ans = 5)

Example 4

Calculate the following trigonometric quantities:

  1. cosπ6 6
  2. tan45 45
  3. sinπ+cos45 45

MATLAB inputs and outputs are as follows:

  1. cos(pi/6) (ans = 0.8660)
  2. tan(45*pi/180) (ans = 1.0000)
  3. 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.

Example 5

Calculate θ=tanπ3 θ 3 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:

Example 6

a = 1

Figure 2: Assignment of a scalar quantity.
Example1

Declaration of a Row Vector

Elements of a row vector are separated with blanks or commas.

Example 7

Let's type the following at the command prompt:

b = [1 2 3 4 5]

Figure 3: Assignment of a row vector quantity.
Example2

We can also use the Variable Editor to assign a row vector. In the menu bar, select File > 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.

Figure 4: Assignment of a row vector by using the Variable Editor.
Example2a

Declaration of a Column Vector

Elements of a column vector is ended by a semicolon:

Example 8

c = [1;2;3;4;5;]

Figure 5: Assignment of a column vector quantity.
Example3

Or by transposing a row vector with the ' operator:

c = [1 2 3 4 5]'

Figure 6: Assignment of a column vector quantity by transposing a row vector with the ' operator.
Example3a

Or by using the Variable Editor:

Figure 7: Assignment of a column vector quantity by using the Variable Editor.
Example3b

Declaration of a Matrix

Matrices are typed in rows first and separated by semicolons to create columns. Consider the examples below:

Example 9

Let us type in a 2x5 matrix:

d = [2 4 6 8 10; 1 3 5 7 9]

Figure 8: Assignment of a 2x5 matrix.
Example4

Figure 9: Assignment of a matrix by using the Variable Editor.
Example4a

Example 10

This example is a 5x2 matrix:

Figure 10: Assignment of a 5x2 matrix.
example4b

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.

Example 11

Let's solve the following simultaneous equations:

x+y=1 x y 1
(1)
2x5y=9 2 x 5 y 9
(2)

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:

( 11 25 ) 1 1 2 5
(3)

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:

( 1 9 ) 1 9
(4)

The above column vector can be entered in the command window by typing B= [1;9].

To solve the simultaneous equation, we will use 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=A\B

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).

ax2+bx+c=0 a x 2 b x c 0
(5)
f(x)=ax2+bx+c f(x) a x 2 b x c
(6)

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.

Example 12

Create a row vector for the following function: y=2x4+3x3+5x2+x+10 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]

Example 13

Create a row vector for the following function: y=3x4+4x25 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.

Example 14

Evaluate f(x) at 5.

f(x)=3x2+2x+1 f(x) 3 x 2 2 x 1
(7)

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:

ax2+bx+c=0 a x 2 b x c 0
(8)

Probably you have solved this type of equations numerous times. In MATLAB, we can use the roots function to find the roots very easily.

Example 15

Find the roots for the following:

0.6x2+0.3x0.9=0 0.6 x 2 0.3 x 0.9 0
(9)

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.

Example 16

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:

Example 17

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

Example 18

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

Table 2: 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

Table 3: 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

Summary of Key Points

  1. MATLAB has the common functions found on a scientific calculator and can be operated in a similar way,
  2. MATLAB can store values in variables. Variables are case sensitive and some variables are reserved by MATLAB (e.g. pi stores 3.1416),
  3. Variable Editor can be used to enter or manipulate matrices,
  4. The coefficients of simultaneous linear equations and polynomials are used to form a row vector. MATLAB then can be used to solve the equations,
  5. The format function is used to control the number of digits displayed,
  6. Three periods "..." at the end of the line is used to split a long statement over multiple lines,
  7. The percent symbol % separates the comments from the code, anything following % symbol is ignored by MATLAB.

Collection Navigation

Content actions

Download:

Collection as:

PDF | EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Module as:

PDF | More downloads ...

Add:

Collection to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks

Module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks