0% found this document useful (0 votes)
13 views

01-Intro_to_MATLAB

ENSC 180 is an introductory course on engineering analysis tools, focusing on MATLAB programming. The course includes lectures and labs, with a grading policy based on labs, assignments, a midterm, and a final exam. Key topics covered include matrix manipulations, plotting, and various MATLAB toolboxes for specific applications.

Uploaded by

David Cross
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

01-Intro_to_MATLAB

ENSC 180 is an introductory course on engineering analysis tools, focusing on MATLAB programming. The course includes lectures and labs, with a grading policy based on labs, assignments, a midterm, and a final exam. Key topics covered include matrix manipulations, plotting, and various MATLAB toolboxes for specific applications.

Uploaded by

David Cross
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

ENSC 180 – Introduction to Engineering Analysis

Lecture 1: Introduction

Prof. Jie Liang


[email protected]
School of Engineering Science
Simon Fraser University
Jan. 7, 2025
Multimedia Communications Laboratory 1
Outline

• Course Information
• Overview of Matlab
• Basic Syntax

ENSC 180 – Introduction to Engineering Analysis Tools 2


Course Information

• Lectures: Tuesdays 2:30 - 4:20 PM, RCBIMAGTH


• Labs: Thursdays 2:30 - 4:20 PM, WMC3520
• Instructor: Prof. Jie Liang, [email protected]
• Office Hours: ASB9843, Tuesday, Thursday, 4:30-5:30pm
• TAs:
• TA Group 1:
• Navid Zare <[email protected]>
• Afrooz Haghbin <[email protected]>
• Masoud Khairi Atani <[email protected]>
• Ricky Chen <[email protected]>
• Hamidreza Ghanbari <[email protected]>
• TA Group 2:
• Anahita Araghi <[email protected]>
• Anderson De Andrade <[email protected]>
• Feng Ding <[email protected]>
• Zanko Rouein <[email protected]>
• Usman Iqbal Ahmed <[email protected]>
• Flexible TA: Soroush Oraki <[email protected]> (Assigned to Group 1 and 2 alternatively)
• TA office hours to be announced

ENSC 180 – Introduction to Engineering Analysis Tools 3


Course Information

• Canvas page:
https://canvas.sfu.ca/courses/89149
Materials will be posted online

• Piazza page for Q&A:


Signup link:
https://piazza.com/sfu.ca/spring2025/ensc180d100

• Course email list: [email protected]


• Only instructor and TAs can send

• Download Matlab on your laptop:


• https://www.sfu.ca/information-systems/services/software/matlab/matlab-install.html
• Need it for labs and exams

• Matlab Online:
• https://www.mathworks.com/products/matlab-online.html

ENSC 180 – Introduction to Engineering Analysis Tools 4


Course Information
• Grading policy:
• 10 Labs: 15%
• Submitted online before the deadline (don’t wait till the last minute)
• The lowest score is dropped.
• 4 Assignments: 15%
• Submitted online on due dates
• Midterm exam: 30%
• Final exam: 40%
• Late submission deduction (for most labs and assignments): 35% per day
• No late submission for labs/assignments before exams.
• The final letter grade generally follows the SFU recommendation, but will be
adjusted slightly by grading on a curve.
https://www.sfu.ca/cee/teaching-resources/new-faculty-resources/faculty-guide-
to-teaching/grading-policies.html
• No extension is allowed except for extenuating circumstances and medical
reasons signed by SFU Health & Counselling Service:
• https://www.sfu.ca/students/health/
• https://www.sfu.ca/content/dam/sfu/students/pdf/certificate-of-illness.pdf
• Grading Rubrics: https://canvas.sfu.ca/courses/89149/rubrics/93108

ENSC 180 – Introduction to Engineering Analysis Tools 5


Course Information

• Please review the SFU plagiarism page:


http://www.sfu.ca/students/academicintegrity.html

• Guidelines on collaborations:
 https://www.haverford.edu/sites/default/files/Department/Math/Guidelines-for-
Homework-Collaboration.pdf
 It is ok to discuss the assignments with others
 Do not read other people’s solutions. Write your own answers and codes.
 Do not become an inactive participant
 Acknowledge your collaborations in your submission

• An assignment containing copied material from others will receive 0 (for


both students).

• Second-time offender will fail the course, and receive the FD grade – Failed for
academic Dishonesty.
• https://www.sfu.ca/students/calendar/2025/spring/fees-and-
regulations/grading-policy/grading-systems-and-policies.html

ENSC 180 – Introduction to Engineering Analysis Tools 6


Course Information

Main Topics 1 Introduction

(Tentative): 2 Scripts, Flow Control & Data Structures

3 Plotting

4 Strings & File IO

5 Combinatorics

6 Probability & Statistics

7 Linear Algebra and System of Linear Equations

8 Complex Numbers

9 Interpolation and Regression

10 Symbolic Computations
11 Numerical Differentiation and Integration
12 Simulink, Compiler, and Review for Exam

Main References
• Physical Modeling in MATLAB, Version 4.0, Allen B. Downey, Green Tea Press, 2021.
• Supporting MATLAB code for the book are in this GitHub repository.
• Experiments with MATLAB, Cleve Moler, 2011.

ENSC 180 – Introduction to Engineering Analysis Tools 7


Outline

• Course Information
• Overview of Matlab
• Basic Syntax

ENSC 180 – Introduction to Engineering Analysis Tools 8


OVERVIEW

• MATLAB: MATrix LABoratory


• Invented by Cleve Moler in 1960’s as a Prof at University of New Mexico
• Co-funded MathWorks in 1984: Chairman and Chief Scientist
• We will use part of his book “Experiments with MATLAB” in this course

• A powerful interpreted programming language for numerical computing:


• Intuitive matrix manipulations
• Convenient plotting of functions and data
• Vast amount of built-in functions: almost anything you can think of
• Simulation tools
• Many Toolboxes
• Rich help documents

ENSC 180 – Introduction to Engineering Analysis Tools 9


Matrix Manipulations

• Matrix multiplication using C++: • Matrix multiplication using Matlab:

vector<vector<int>> A = { {1, 2, 3},


{4, 5, 6},
>> A = [1, 2, 3; 4, 5, 6; 7, 8, 9];
{7, 8, 9}}; >> B = [9, 8, 7; 6, 5, 4; 3, 2, 1];
vector<vector<int>> B = {{9, 8, 7}, >> C = A * B
{6, 5, 4},
{3, 2, 1}};
C=
int rows1 = A.size();
int cols1 = A[0].size();
int rows2 = B.size(); 30 24 18
int cols2 = B[0].size(); 84 69 54
vector<vector<int>> C(rows1, vector<int>(cols2, 0));
138 114 90

for (int i = 0; i < rows1; ++i) {


for (int j = 0; j < cols2; ++j) { • No need to define data types
for (int k = 0; k < cols1; ++k) { • No need to do all the housekeeping
C[i][j] += A[i][k] * B[k][j];
} • Focus on the math problem itself, not
} programming details
}

ENSC 180 – Introduction to Engineering Analysis Tools 10


Interpreted Language vs Compiled Language

• MATLAB is an interpreted language, not compiled language (such as C/C++)


• Has tools to compile Matlab codes into C/C++, VHDL, or standalone applications
and web apps.

Compiled Language Interpreted Language

1 Compiled language follows at Interpreted language follows one step to get


least two steps to get from from source code to execution.
source code to execution.
2 A compiled language is An interpreted language is a language in
converted into machine code which the implementations execute
so that the processor can instructions directly without compiling a
execute it. program into machine language.
4 The compiled programs run The interpreted programs run slower than
faster than interpreted the compiled program.
programs.
5 In a compiled language, the In Interpreted languages, the program
code can be executed by the cannot be compiled, it is interpreted.
CPU.
6 This language delivers better This language delivers slower performance.
performance.

ENSC 180 – Introduction to Engineering Analysis Tools 11


Plotting

• Plotting the Matlab Logo:

L = 160 * membrane(1,100);
f = figure;
ax = axes;
s = surface(L);
s.EdgeColor = 'none';
view(3)

s.FaceColor = [0.9 0.2 0.2];

https://www.mathworks.com/help/matlab/visualize/creating-the-matlab-logo.html

ENSC 180 – Introduction to Engineering Analysis Tools 12


Simulation Tools

• Time-Based Simulation: Simulink


• A communication modulation
example:

https://www.mathworks.com/discovery/simulation-software.html
https://electrosome.com/am-generation-simulink/
ENSC 180 – Introduction to Engineering Analysis Tools 13
Simulation Tools

• Event-Based Simulation: Stateflow

• A graphical language that includes state transition


diagrams, flow charts, state transition tables, and
truth tables.

• Stateflow can call Simulink blocks

• Describe how MATLAB algorithms and Simulink


models react to input signals, events, and time-based
conditions.

https://www.mathworks.com/products/stateflow.html

ENSC 180 – Introduction to Engineering Analysis Tools 14


Simulation Tools

• State machine for changing gear when driving a car:

https://www.mathworks.com/products/stateflow.html

ENSC 180 – Introduction to Engineering Analysis Tools 15


Simulation Tools

• Physical Systems Simulation: Simscape


• Rapidly create models of physical systems within the
Simulink environment:

• Simulink uses block diagram approach. The signal


flow is unidirection.
• Simscape uses physical modeling approach. The
signal flow is bi-directional between blocks.

• There is a source code provided for each block in


Simscape, which can be changed by users.

https://www.mathworks.com/help/simscape/

ENSC 180 – Introduction to Engineering Analysis Tools 16


Simulation Tools

• Example: Simulation of SpaceX Crew Dragon

https://twitter.com/MATLAB/status/1290603083727286274

ENSC 180 – Introduction to Engineering Analysis Tools 17


Simulation Tools

• Example: A DIY version of Rocket Takeoff and Landing


Simulation using Matlab & Simulink

https://www.youtube.com/watch?v=jI0eWIgXsT4

ENSC 180 – Introduction to Engineering Analysis Tools 18


Toolboxes

• A toolbox is a package of functions for a specific topic.


• Examples:
• Symbolic math toolbox
• Optimization toolbox
• Communications toolbox
• Control system toolbox
• DSP system toolbox
• Image processing toolbox
Can be installed from the
• Robotics system toolbox
Add-Ons menu.
• Signal processing toolbox
• Statistics and machine learning toolbox
• Deep learning toolbox
• Parallel computing toolbox

ENSC 180 – Introduction to Engineering Analysis Tools 19


Toolboxes

Example: Use Symbolic Math Toolbox to find the 1st and 2nd derivative of f(x)
https://www.mathworks.com/help/symbolic/differentiation-featured.html
% declare symbolic variables
syms x
assume(x, 'real’)
f = (3*x^3 + 17*x^2 + 6*x + 1)/(2*x^3 - x + 3)

g = diff(f, x)

h = diff(f, x, 2)

ENSC 180 – Introduction to Engineering Analysis Tools 20


Toolboxes

• Example: Deep Learning Toolbox:


• Deep neural networks: the driving force of the current AI revolution

https://www.mathworks.com/videos/what-is-deep-learning-toolbox--1535667599631.html

ENSC 180 – Introduction to Engineering Analysis Tools 21


Help

• help ***: will display the help info of the function in the command window
• doc ***: will open the Help Center window and display more extensive help
>> help sin
sin Sine of argument in radians.
sin(X) is the sine of the elements of X.

See also asin, sind, sinpi.

Documentation for sin


Other uses of sin

• Online Help Center:


https://www.mathworks.com/help/index.html

ENSC 180 – Introduction to Engineering Analysis Tools 22


Outline

• Course Information
• Overview of Matlab
• Basic Syntax

ENSC 180 – Introduction to Engineering Analysis Tools 23


Matlab User Interface

Script editor window

Workspace
Window

Command Window

ENSC 180 – Introduction to Engineering Analysis Tools 24


COMMAND WINDOW

• All examples in this presentation make use of the MATLAB command window.
• Variable: A named value.

• Assignment: assign a value to a variable


>> a = 10
a =
10

• Suppress output: place a semicolon ; at the end of a command.

>> a = 10;
>>

• Command History: Press ↑ to cycle through previous commands

• Clear Command Window display: the command history is not cleared


>> clc

ENSC 180 – Introduction to Engineering Analysis Tools 25


VARIABLE TYPES
• No need to define variable type (default type: double-precision floating-point)
>> a = 10 >> str = 'm'
a = str =
10 m

>> bool_var = true >> complex_num = 2 + 8*j


bool_var = complex_num =
1 2.0000 + 8.0000i
• Workspace Window: Display variables in the current workspace.
• who: list names of current variables
• whos: list more info of current variables: name, size, bytes, class, attributes.
>> who
a bool_var complex_num str
>> whos
Name Size Bytes Class Attributes
a 1x1 8 double
bool_var 1x1 1 logical
complex_num 1x1 16 double complex
str 1x1 2 char
• clear ***: delete specified variables from the workspace
• clear all: delete all variables
ENSC 180 – Introduction to Engineering Analysis Tools 26
VARIABLE NAMES

• Variable names cannot begin with a number.


• Names are case-sensitive and have a maximum length of namelengthmax (63
for MATLAB R2023).
• Spaces cannot be used; use underscores _ instead.
• To prevent naming conflicts, use the exist function to check:
>> exist pi >> exist size >> exist var_name
ans = ans = ans =
5 5 0
• Return value (type “help exist” for details):
• 0: name does not exist
• 1: name is a variable in the workspace
• 5: name is a build-in function
• Some built-in variables:
• i and j: imaginary units.
• ans : the most recent answer when no output argument is specified.
• Inf and NaN : positive infinity and “Not-a-Number”.
• pi : floating point number that closest approximates the value of π.

ENSC 180 – Introduction to Engineering Analysis Tools 27


ARRAYS

• Row Vector: To put data in a row vector, type values within square brackets that
are separated by commas or spaces:

>> b = [3, 8, 4, 1, 2]
b =
3 8 4 1 2

• Column Vector: To put data in a column vector, type values within square brackets
that are separated by semicolons. The semicolon represents the end of a row.

>> c = [2; 9; 5]
c =
2
9
5
 Transpose operator: ‘ (the prime or single quote symbol)
 c = [2, 9, 5]’ will create the same column vector as above

ENSC 180 – Introduction to Engineering Analysis Tools 28


Matlab Data Types

• Matlab has 17 different data types (also called classes):

https://www.mathworks.com/help/matlab/matlab_prog/fundamental-matlab-classes.html

ENSC 180 – Introduction to Engineering Analysis Tools 29


MATRICES

• To create a matrix, just combine the row and column vector syntax.
• Use commas or spaces to fill in the rows.
• Use a semi-colon to end the row and start a new one.

>> A = [1 2 3; 4 5 6; 7 8 9; 10 11 12]
A =
1 2 3
4 5 6
7 8 9
10 11 12

• The example here illustrates a double-precision floating-point matrix


• Matrices can also store other data types, such as strings, logical states, unsigned
integers, complex numbers, etc.

ENSC 180 – Introduction to Engineering Analysis Tools 30


COLON OPERATOR

• The colon is one of the most useful operators in MATLAB.


• It can be used to simplify array and matrix creation:
• j:k creates an array [j, j+1, j+2, …, k] or empty when j > k.
• j:i:k is similar except it uses a step size i: [j, j+i, j+2*i, …].

Can be used to generate arrays and matrices:

>> B = [1:5; 2:3:15; -2:0.5:0]


B =
1.0000 2.0000 3.0000 4.0000 5.0000
2.0000 5.0000 8.0000 11.0000 14.0000
-2.0000 -1.5000 -1.0000 -0.5000 0

• Also works with characters:

>> str = 'a':2:'z'


str =
acegikmoqsuwy

ENSC 180 – Introduction to Engineering Analysis Tools 31


CONCATENATION

• A matrix is a rectangular data structure.


• Matrices and arrays can be formed through concatenation as long as the
rectangular shape is preserved

• Concatenation works with all the array creation syntax taught thus far:

>> C = [1 2; 3 4]; F =
>> D = [9 9; 9 9]; 1 2 9 9
>> E = 5:8; 3 4 9 9
>> F = [C D; E; -2:1]; 5 6 7 8
-2 -1 0 1

ENSC 180 – Introduction to Engineering Analysis Tools 32


ARITHMETIC OPERATORS

• Some mathematical operations in MATLAB are fairly straightforward:


• +, - Addition, subtraction
• () Round brackets specifies order of operations.

• However, others are not as clear-cut:


• *, / Matrix multiplication and division.
• .*, ./, .^ Element-wise multiplication, division, and power.

• Matrices of the same size can be added or subtracted:

>> A = [10 20 30; 40 50 60] >> C = A + B


>> B = [2 3 4; 7 8 9] C =
12 23 34
47 58 69

ENSC 180 – Introduction to Engineering Analysis Tools 33


MATRIX MULTIPLICATION

• Be careful when using the * operation.


• When multiplying scalars, it can be used without worry.
• When multiplying matrices, their sizes need to meet matrix multiplication rule.

• Matrix Multiplication Rule:

p
n p
>> A = [1 2 3; 4 5 6] m =m
A =
n
1 2 3
4 5 6
>> A * B
>> B = [2 2 10; 10 10 10] Error using *
Incorrect dimensions for matrix multiplication. Check
B = that the number of columns in the first matrix matches
2 2 10 the number of rows in the second matrix. To operate on
10 10 10 each element of the matrix individually, use TIMES
(.*) for elementwise multiplication.

ENSC 180 – Introduction to Engineering Analysis Tools 34


MATRIX MULTIPLICATION

• But we can multiply A with transpose of B:


>> A = [1 2 3; 4 5 6];
>> B = [2 2 10; 10 10 10];
>> C = A * B’ 2 2
C = 3
36 60 2 = 2
78 150 3

• Or multiply transpose of A with B:

>> A' * B
2 3
ans =
3
3 2 = 3
42 42 50
54 54 70
66 66 90

ENSC 180 – Introduction to Engineering Analysis Tools 35


ELEMENT-WISE MATRIX OPERATIONS

• .*, ./, .^ Element-wise multiplication, division, and power.


• Applying the operator to corresponding elements.
• The sizes of A and B must be the same or be compatible.
>> C = A .* B
>> A = [1 2 3; 4 5 6]; C =
>> B = [2 2 10; 10 10 10]; 2 4 30
40 50 60
>> C = 2 .* A
• Compatible Cases: C =
2 4 6
• 1) one of A or B is a scalar: 8 10 12  Same as 2 * A

• 2) A and B are vectors with different orientations: a .* b


ans = 4×3
>> a = 1:3 >> b = (1:4)'
a = b = 1 2 3
1 2 3 2 4 6
1 3 6 9
2 4 8 12
3
4 b .* a: Same result !

ENSC 180 – Introduction to Engineering Analysis Tools 36


OTHER METHODS OF ARRAY CREATION

• There are various built-in functions that are useful for creating arrays and matrices:
• Built-in functions generally run faster than manual implementations

• ones() and zeros() – Array of all ones and all zeros, respectively.
• eye() – Identity matrix.
• diag() – Diagonal matrices and diagonals of a matrix.
• true() and false() – logical 1 and logical 0 matrices, respectively.
• linspace() – create linearly spaced vectors.
• ndgrid() – rectangular grid in N-D space.
• [x1,x2,x3] = ndgrid(-2:.2:2, -2:.25:2, -2:.16:2);
•rand() – Uniformly distributed pseudorandom numbers in (0, 1)
• randn() – Normally distributed pseudorandom numbers: zero mean, unit
variance

>> 2 * ones(1,20); %row vector with 20 elements, all 2


>> eye(5); %5x5 identity matrix
>> linspace(0,13,6); %row vector that starts with 0, ends
with 13, and has 6 values

ENSC 180 – Introduction to Engineering Analysis Tools 37


BUILT-IN FUNCTIONS

• All MATLAB functions have the following form:


[output1, output2, ...] = function(arg1, arg2, ...)

• Standard math functions such as sin, cos, and sqrt are readily available and
operate element-wise on any matrix:

>> sin([0, pi/4, pi/2])


ans =
0 0.7071 1.0000

• Many functions will have outputs that differ in size or type from the inputs:

>> A = [1 2 3; 4 5 6];
>> [num_row, num_col] = size(A)

num_row = num_col =
2 3

ENSC 180 – Introduction to Engineering Analysis Tools 38


FUNCTIONS RELATED TO ARRAY SIZE

• size( ): Size of array.


• length( ): Length of vector, equivalent to MAX(SIZE(X)).
• height( ): Number of rows in an array.
• ndims( ): Number of dimensions: LENGTH(SIZE(X)).
• numel( ): Number of elements in an array: equivalent to PROD(SIZE(A)).

>> A = [1 2 3; 4 5 6] >> size(A)


A = ans =
1 2 3 2 3
4 5 6

>> length(A) >> height(A) >> ndims(A) >> numel(A)


ans = ans = ans = ans =
3 2 2 6

ENSC 180 – Introduction to Engineering Analysis Tools 39


INDEXING BY POSITION

• Indexing is used to select a certain subset of elements inside a matrix.


• A crucial part of eliminating loops and optimizing MATLAB code, since it allows
vector operations to be used.
• 1: Indexing by Position: The entry of a matrix A at a specific row and column can
be obtained using the syntax: A(row, column).

>> A = magic(4)
A =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1

>> A(4,2)
ans =
14

Note: Matlab indexing starts from 1 (C/C++ indexing starts from 0)

ENSC 180 – Introduction to Engineering Analysis Tools 40


INDEXING BY POSITION

• The colon operator allows multiple entries to be accessed:

>> A(3, 1 : 2) >> A(3, :)


ans = ans =
9 7 9 7 6 12

• A(3, :) means matrix A, row 3, all columns.


• We can also use the square bracket notation:

>> A([1 2], :)


ans =
16 2 3 13
5 11 10 8

• This is read: matrix A, row 1 and 2, all columns.

ENSC 180 – Introduction to Engineering Analysis Tools 41


INDEXING BY POSITION

• This can also be used to manipulate data within the matrix, e.g.: set matrix A, rows
1 to 3, columns 3 to 4, equal to 0:

>> A(1:3, 3:4) = 0


A =
16 2 0 0
5 11 0 0
9 7 0 0
4 14 15 1

• We can also remove entries by setting them equal to []:

>> A(2:2:4,:) = []
A = 16 2 0 0
9 7 0 0

ENSC 180 – Introduction to Engineering Analysis Tools 42


LINEAR INDEXING

• Matlab stores arrays in memory as a big single column vector, made up of all
columns of A appended one after the other.
• 2: Linear Indexing: Therefore elements of an array can also be accessed by a
single index, regardless of the size or dimensions of the array.

>> A >> A(4)


A = ans =
16 2 0 0 7
9 7 0 0

https://www.mathworks.com/help/matlab/math/array-
indexing.html?searchHighlight=linear%20index&s_tid=srchtitle_support_results_1_linear%20index

ENSC 180 – Introduction to Engineering Analysis Tools 43


LINEAR INDEXING

• Any matrix or row vector can be transformed into a column vector using the colon
operator in round brackets:

>> A = magic(2) >> B = A(:) >> sum(A(:))


A = B = ans =
1 10
1 3
4
4 2
3
2

What is the output of sum(A)? A row vector with the sum over each column.
>> sum(A)
ans =
5 5

General reshape function:


• B = reshape(A,M,N) or reshape(A,[M,N]):
• Returns the M-by-N matrix whose elements are taken columnwise from A.
• A must have M*N elements.

ENSC 180 – Introduction to Engineering Analysis Tools 44


LOGICAL OPERATORS

• Logical statements are evaluated to return true or false, which is denoted by 0 or 1


(logical data type), respectively.
• The following are some element-wise operations (can be applied to matrix):
> greater than ~ logical NOT
< less than & logical AND
== equal | logical OR
~= not equal

• Logical operators with short-circuiting:


• expr1 && expr2 logical AND with short-circuiting, expr2 is not
evaluated if expr1 is 0 (false).
• Example: if (expr1 && expr2)
• expr1 || expr2 logical OR with short-circuiting, expr2 is not
evaluated if expr1 is logical 1 (true).
• expr1 and expr2 should be a scalar logical operator, not vector or matrix

• Full list of Matlab operators:


https://www.mathworks.com/help/matlab/matlab_prog/matlab-operators-and-
special-characters.html

ENSC 180 – Introduction to Engineering Analysis Tools 45


LOGICAL OPERATORS

• In the following example, b is a logical array that shows which values of a are
less than or equal to 5.

>> a = [1 8 4 5 2 -2 9];
>> b = a <= 5
b =
1 0 1 1 1 1 0

• The array c indicates which values of a are greater than 0.

>> c = a > 0
c =
1 1 1 1 1 0 1

• How many entries are > 0? • Find indices of a > 5?


>> sum(a > 0) >> find(a > 5)
ans = ans =
6 2 7

ENSC 180 – Introduction to Engineering Analysis Tools 46


LOGICAL INDEXING
>> a = [1 8 4 5 2 -2 9];

• We may then determine which values of a are between 5 (inclusive) and 0


(exclusive), i.e. 0 < a ≤ 5:

>> d = b & c
d =
1 0 1 1 1 0 0

• Note: Cannot use b && c here, because b and c are arrays, not scalar.

• 3: Logical Indexing: We can use the logical operator result to extract these values
correspond to value 1 in the logical result, or modify them.

>> a(d) >> a(d) = 27


ans = a =
1 4 5 2 27 8 27 27 27 -2 9

ENSC 180 – Introduction to Engineering Analysis Tools 47


INFINITY AND UNDEFINED DATA

• MATLAB represents infinity by inf and automatically assigns this value to


operations that divide by 0 or result in overflow.

>> x = 1 / 0 >> x = exp(1000) >> x = log(0)


x = x = x =
Inf Inf -Inf

• The value NaN (Not-a-Number) is assigned to undefined outputs.

>> x = [0/0, 8/0, 23, 3^1000, inf/inf]


x =
NaN Inf 23 Inf NaN

• Built-in logical functions are available to identify these special values.

>> isnan(x)
ans =
1 0 0 0 1

Other functions: isinf, isfinite

ENSC 180 – Introduction to Engineering Analysis Tools 48

You might also like