0% found this document useful (0 votes)
30 views67 pages

CE-111 Introduction To Computing For Civil Engineers

Uploaded by

Arifah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views67 pages

CE-111 Introduction To Computing For Civil Engineers

Uploaded by

Arifah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

CE-111

Introduction to
Computing for Civil
Engineers

Lecture 7
Recap
• Examples related to control structures
• Function programming in python

Lecture 08 2
Road Map for Today
• MATLAB
– BASIC ARITHMETIC IN MATLAB
– ARRAYS

Lecture 08 3
3. MATLAB

Lecture 08 4
3.1 What is MATLAB?
• MATLAB stands for Matrix Laboratory.
• MATLAB is a high-performance language for technical computing.
• It integrates
– computation,
– visualization, and
– Programming
• All of the above in an easy-to-use environment where problems
and solutions are expressed in familiar mathematical notation.
3.2 Typical Uses of MATLAB
• Math and computation
• Algorithm development
• Modelling, simulation, and prototyping
• Data analysis, exploration, and visualization
• Scientific and engineering graphics
• Application development, including Graphical User Interface
building
3.3 Main MATLAB Window
Getting Help
• There are several ways of getting help:

– Basic help on named commands/functions is echoed to the command


window by:

>> help command-name

– A complete help system containing full text of manuals is started by:

>> helpdesk
Getting Help
Getting Help
3.2 Arithmetic Operators
• MATLAB uses conventional decimal notation with option
decimal point, for numbers.
• The e or E notation is used for very large or very small
numbers. So
1.2345e-89 means 1.2345×10-89
• Either the 𝑖𝑖 or 𝑗𝑗 notation can be used to represent the
imaginary unit in a complex number.
Legitimately expressed numbers

3 -99 0.0001
9.63978 1.6021E-20 6.0223e23
2*i -3.141*i 3e5*i
Predefined Constant Values
• Example of a simple interactive session:
– suppose you want to calculate the expression, 1 + 2 × 3.
– The expression is typed at the command prompt (>>) as follows:
Using MATLAB as a calculator (cont…)
• MATLAB uses default variable ans, short for answer, to store
the results of the current calculation.
• Note: variable ans is created (or overwritten if it already
exists!)
• To avoid we assign a value to a variable or output argument.
Using MATLAB as a calculator (cont…)
• The variable name can always be used to refer to the results of
the previous computations.
Basic list of arithmetic operators:

+ Addition
- Subtraction
* Multiplication
/ Division
^ power
3.2.1 Controlling the hierarchy of Operations or
Precedence
• If we consider the two expressions, the two parentheses
give different results:

• The order in which MATLAB performs arithmetic operations


is exactly that taught in high school algebra courses.
• Exponentiations are done first, followed by multiplications
• and divisions, and finally by additions and subtractions.
• However, the standard order of precedence of arithmetic
operations can be changed by inserting parentheses
• Parentheses can always be used to overrule priority, and
their use is recommended in some complex expressions to
avoid ambiguity.
Precedence Rules

• Example
>> 2+2/4*5
ans =
5.75

Performing the computation 2+3/4×5=2+0.75×5=2+3.75=5.75


Example
3.2.2 Variables
• MATLAB displays the result of any assignment on the screen, and assigns it to the
specific variable, or to ans if no variable is given.
• Examples

>> 3-2^4 >> x=3-2^4


ans = The result of the first x= You can assign the
-13 calculation is assigned to -13 result of a calculation
>> ans*5 the default variable ans, >> y=x*5
ans = when may then be used y= to variable names of
-65 in the next calculation. -65 your own choice.

• You can assign the result of calculation to a variable retrospectively


by using the command x=ans, which assigns the result of
unassigned calculation (as ans) to the variable x.
• These values can be used in subsequent calculations.
Legitimate Variable Names
• Can consist of any combination of letters and digits provided
the combination starts with a letter (but does not include
special characters such as ! $ % &, etc).
• Legal variables
NetCost, Left2Pay, theta1, x1, z25c4
• Combination that are NOT acceptable
Net-Cost, 2Pay, 1x, %theta
3.2.3 Controlling the Output
• if you do not wish to see the intermediate results, you can suppress the
numerical output by putting a semicolon (;) at the end of the line.
• It is possible to enter multiple statements per line.
• Use commas (,) or semicolons (;) to enter more than one statement at
once.
• Commas (,) allow multiple statements per line without suppressing output.
Controlling the Output (cont…)
• MATLAB by default displays only 4 decimals in the result of
the calculations, for example -163.6667.
• All computations in MATLAB are done in double precision,
referring to accuracy of about 15 significant figures.
>> 2/7
ans =
0.2857

• While only 4 significant figures have been displayed, MATLAB


has actually done the calculation to a much higher accuracy.
• Issuing the format long command gives
>> format long
>> 2/7
ans =
0.28571428571429
format command
• Controls the format of the output.
MATLAB Command Example of output
format short 1.3333 (5 digits)
format shore e 1.3333e+000 (floating point with 5 digits)
format long 1.33333333333333 (15 digits)
format long e 1.33333333333333e+000 (15 digits)
format compact Suppresses extra lines feeds
format loose Puts the extra line feeds back in (default)

• The default format is short, and then MATLAB displays all numeric
output to 5 digits.
3.2.4 Entering Complex Values
• MATLAB allows complex numbers in all its operations and
functions.
• You may use either symbols 𝑖𝑖 or 𝑗𝑗 to represent −1. Examples
>> z=3+4*i
z=
3.0000+4.0000i
>> w=z^2
z=
-7.0000+24.0000i
>> conj(w)
z=
-7.0000-24.0000i
>> abs(z)
ans =
5

• conj and abs have the meanings of complex conjugate and


absolute value respectively.
Elementary Functions
3.2.5 Error messages
• If an expression is incorrectly entered, MATLAB will return an
error message.
• For example, leaving out the multiplication sign * in the
following example:
3.2.6 Making Corrections
• To make corrections, we can, of course retype the expressions.
• But if the expression is lengthy, we make more mistakes by
typing a second time.
• A previously typed command can be recalled with the up-
arrow key ↑.
• When the command is displayed at the command prompt, it
can be modified if needed and executed.
3.2.7 Managing Workspace
• The contents of the workspace persist between the executions of separate commands.
• Therefore, it is possible for the results of one problem to have an effect on the next one.
• To avoid this possibility, it is a good idea to issue a clear command at the start of each new
independent calculation.
>> clear
• The command clear or clear all removes all variables from the workspace.
• Thisfrees up system memory.
• In order to display a list of the variables currently in the memory, type
>> who
• while, whos will give more details which include size, space allocation, and class of the
variables.
3.2.8 Keeping track of your work session
• It is possible to keep track of everything done during a MATLAB
session with the diary command.
>> diary
• Or give a name to a created file,
>> diary FileName
where FileName could be any arbitrary name you choose.
Keeping track of you work session
• The function diary is useful if you want to save a complete MATLAB session.
• They save all input and output as they appear in the MATLAB window.
• When you want to stop the recording, enter diary off. If you want to start
recording again, enter diary on.
• The file that is created is a simple text file.
• It can be opened by an editor or a word processing program and edited to
remove extraneous material, or to add your comments
• You can use the function type to view the diary file or you can edit in a text
editor or print.
• This command is useful, for example in the process of preparing a homework or
lab submission.
3.2.9 Quitting MATLAB
• To end your MATLAB session, type quit in the Command
Window, or select File → Exit MATLAB in the desktop main
menu.
3.3 Arrays and Matrices
• Discuss Arrays, some syntax and built in functions all together
– syntax and built in functions come up while learning arrays
3.3.1 Arrays
• MATLAB is adept at handling arrays
– Optimized for vector/matrix operations
– This allows for a reduction of code in some cases
• Array types: Numeric, character, logical, cell, structure,
function handle
– Numeric types: single, double, int8, int16, int32, uint8, uint16, uint32
3.3.1.1 Numeric Arrays
• One dimensional arrays, called vectors
– Can create row or column vectors
– Row vector
• A few ways to create a row vector

• Or use “:”
Numeric Arrays
• Column vectors
– A few ways to generate column vectors too
– Semicolon between elements starts new row
– Transpose a row vector, or use return between elements
Numeric Arrays
• You can also append vectors into one big row or column vector
• Use built in function to generate vectors
– linspace
• Create a row vector of linearly spaced elements
– logspace
• Create a row vector of logarithmically spaced elements
Numeric Arrays
• Two-dimensional arrays, called a matrix in MATLAB often
• Size = rows by columns
– [r c] = size(array_name) if array_name is a matrix
– size will work for n-dimension arrays and output size of each
dimension into a row vector
• Basic matrix creation:
Numeric Arrays
• Array addressing
– Vector: foo
• foo(:) gives all row or column elements
• foo(1:5) gives the first five row or column elements
• foo(2) gives the second element
– Matrix: bar
• bar(1,3) gives the first row, third column element
• Bar(:,2) gives all elements in the second column
• Bar(1,:) gives all elements in the first row
• Bar(3:4,1:3) gives all elements in the third and fourth rows that are in the first
through third columns
Numeric Arrays
• Array operations
– MATLAB has array or element by element and matrix operations
when dealing with arrays
• Element-by-element operations
– Multiplying a vector or array by a scalar is an easy example
Numeric Arrays
• How do you multiply two arrays element-by-element?
– Do it in a for loop
• Very slow, avoid whenever possible
– Use element-by-element operations
– Addition and subtraction are the same: +, -
– Multiplication, right and left division and exponentiation use “.”
before the symbol
• i.e. foo.*bar or foo./bar or foo.^3
Numeric Arrays
• Examples of element-by-element operation results
Numeric Arrays
• Matrix operations
– Matrix operations are the same symbols as
standard scalar operations
– Apply when multiplying or dividing matrices
Numeric Arrays
• Useful built-in functions for working with
arrays
– Size, linspace and logspace were already
mentioned
– Num_of_elements = length(array)
• Returns the length of the longest dimension
– Max_val = max(array)
• Returns the largest element in the array if it is a vector
• Returns a row vector of the largest element if the array
is a matrix
– min_val = min(array)
• Same as max, but returns the minimum values
Numeric Arrays
• sum(array)
– Returns the sum of a vector or a row vector of the sum of each
column
• find(array)
– Returns an array with the locations of the nonzero elements of the
array
– Will talk about find more in week 4
Numeric Arrays
• When dealing with numeric arrays, the clear function can
come in handy
– If you have foo declared as a 2x2 array
– Then create two 5x1 arrays, x and y
– Try to do: foo(:,1) = x
– Produces an error because MATLAB thinks foo should be a 2x2 array
and x won’t fit into the first column of foo
– Use clear to reset foo
Numeric Arrays
• MATLAB can create several special matrices
– Identity, zeros and ones
– Useful for initializing matrices to ones, zeros or when you may need
to use the identity matrix
• MATLAB also has functions to check for NaN, inf, or if an array
is empty
– isnan, isempty, isinf
3.3.1.2 Determinant of a Matrix
• The determinant of a square matrix in MATLAB is determined
by the simple command det(A). Thus, if a is to represent the
determinant, we would type and enter
>> a = det(A)
• Note that a is a scalar (1 x 1 "matrix").

49
3.3.1.3 Inverse Matrix

• The inverse of a square matrix in MATLAB is


determined by the simple command inv(A).
Thus, if B is to represent the inverse of A ,
the command would be

>> B = inv(A)

50
3.3.1.4 Simultaneous Equation
Solution
Ax = b
-1
x=A b
• MATLAB Format:
>> x = inv(A)*b

• Alternate MATLAB Format:


>> x = A\b
51
Example 1: Enter the matrices below in MATLAB.

2 1 
 2 -3 5  
A=  B = 7 -4 
-1 4 6  3 1 
>> A = [2 -3 5; -1 4 6];

>> B = [2 1; 7 -4; 3 1];

52
Example 2: Determine the transpose of B and
denote it as C.

>> C = B'
C=
2 7 3
1 -4 1

• The 3 x 2 matrix has been converted to a 2


x 3 matrix.

53
Example 3: Determine the sum of A and C and denote it as D.

>> D = A + C
D=
4 4 8
0 0 7

54
Example 4: Determine the product of A and B with A first.

>> A*B
ans =
-2 19
44 -11

55
Example 5: Determine the product of B and A with B first.

>> B*A
ans =
3 -2 16
18 -37 11
5 -5 21

56
Example 6. Determine the array product of A and C and
denote it as E.

>> E = A.*C
E=
4 -21 15
-1 -16 6

57
Example 7: Enter the matrix A. It will be used in several
examples.

 1 2 -1

A = -1 1 3 
 3 2 1 
>> A = [1 2 -1; -1 1 3; 3 2 1]
A=
1 2 -1
-1 1 3
3 2 1
58
Example 7: (cont…) Determine the determinant of A and
denote it as a.

>> a = det(A)
a=
20

59
Example 8. Determine the inverse matrix of A and denote
it as Ainv.

>> Ainv = inv(A)

Ainv =
-0.2500 -0.2000 0.3500
0.5000 0.2000 -0.1000
-0.2500 0.2000 0.1500

60
Example 9: Use MATLAB to solve the
simultaneous equations below.

x1 + 2 x2 − x3 =−8
− x1 + x2 + 3 x3 =7
3 x1 + 2 x2 + x3 =
4
61
Example 9: (Cont…)

• Assume that A is still in memory.

>> b = [-8; 7; 4]
b=
-8
7
4

62
Example 9: (Cont…)

>> x = inv(A)*b

x=
2.0000
-3.0000
4.0000

63
Example 9: (Cont…)
• Alternately,

>> x = A\b
x=
2.0000
-3.0000
4.0000

64
Exercise 1
1. Evaluate the following MATLAB expressions by hand and use
MATLAB to check the answers.
a) 2/2*3
b) 6-2/5+7^2-1
c) 10 / 2 \ 5 - 3 + 2 * 4
d) 3^2/4
e) 3^2^2
f) 2 + round(6 / 9 + 3 * 2) / 2 - 3
g) 2 + floor(6 / 9 + 3 * 2) / 2 - 3
h) 2 + ceil(6 / 9 + 3 * 2) / 2 - 3
Exercise 1
2. Evaluate the following mathematical expressions in MATLAB.
Display your evaluations by omitting semicolons at the end of
your lines.
a) 28
22
b) − 𝜋𝜋
7
4 192
c) 92 + − 𝜋𝜋
22
d) 𝜋𝜋 − 𝑒𝑒 𝜋𝜋
e) log 10 2
f) tanh 𝑒𝑒
Exercise 1 (cont…)
3. Evaluate the following expressions, omitting semicolons at the
ends of your lines. You should have the format short (the default)
in effect for all but the last two items.

a) 1⁄0
b) 0⁄0
c) 1 − 10−8
d) 1 − 10−20
e) 1 − 10−8 with format long in effect
f) 1 − 10−20 with format long in effect

You might also like