You are on page 1of 216

1

Introduction

What Is MATLAB? (p. 1-2) See how MATLAB® can provide solutions for you in technical
computing, what are some of the common applications of
MATLAB, and what types of add-on application-specific
solutions are available in MATLAB toolboxes.
MATLAB Documentation (p. 1-4) Find out where to look for instruction on how to use each
component of MATLAB, and where to find help when you need
it.
Starting and Quitting MATLAB Start a new MATLAB session, use the desktop environment,
(p. 1-6) and terminate the session.
1 Introduction

What Is MATLAB?
MATLAB® is a high-performance language for technical computing. It
integrates computation, visualization, and programming in an easy-to-use
environment where problems and solutions are expressed in familiar
mathematical notation. Typical uses include

• Math and computation


• Algorithm development
• Data acquisition
• Modeling, simulation, and prototyping
• Data analysis, exploration, and visualization
• Scientific and engineering graphics
• Application development, including graphical user interface building

MATLAB is an interactive system whose basic data element is an array that


does not require dimensioning. This allows you to solve many technical
computing problems, especially those with matrix and vector formulations, in
a fraction of the time it would take to write a program in a scalar noninteractive
language such as C or Fortran.
The name MATLAB stands for matrix laboratory. MATLAB was originally
written to provide easy access to matrix software developed by the LINPACK
and EISPACK projects. Today, MATLAB engines incorporate the LAPACK
and BLAS libraries, embedding the state of the art in software for matrix
computation.
MATLAB has evolved over a period of years with input from many users. In
university environments, it is the standard instructional tool for introductory
and advanced courses in mathematics, engineering, and science. In industry,
MATLAB is the tool of choice for high-productivity research, development, and
analysis.
MATLAB features a family of add-on application-specific solutions called
toolboxes. Very important to most users of MATLAB, toolboxes allow you to
learn and apply specialized technology. Toolboxes are comprehensive
collections of MATLAB functions (M-files) that extend the MATLAB
environment to solve particular classes of problems. Areas in which toolboxes
are available include signal processing, control systems, neural networks,
fuzzy logic, wavelets, simulation, and many others.

1-2
What Is MATLAB?

The MATLAB System


The MATLAB system consists of five main parts:

Development Environment. This is the set of tools and facilities that help you use
MATLAB functions and files. Many of these tools are graphical user interfaces.
It includes the MATLAB desktop and Command Window, a command history,
an editor and debugger, and browsers for viewing help, the workspace, files,
and the search path.

The MATLAB Mathematical Function Library. This is a vast collection of computational


algorithms ranging from elementary functions, like sum, sine, cosine, and
complex arithmetic, to more sophisticated functions like matrix inverse, matrix
eigenvalues, Bessel functions, and fast Fourier transforms.

The MATLAB Language. This is a high-level matrix/array language with control


flow statements, functions, data structures, input/output, and object-oriented
programming features. It allows both “programming in the small” to rapidly
create quick and dirty throw-away programs, and “programming in the large”
to create large and complex application programs.

Graphics. MATLAB has extensive facilities for displaying vectors and matrices
as graphs, as well as annotating and printing these graphs. It includes
high-level functions for two-dimensional and three-dimensional data
visualization, image processing, animation, and presentation graphics. It also
includes low-level functions that allow you to fully customize the appearance of
graphics as well as to build complete graphical user interfaces on your
MATLAB applications.

The MATLAB External Interfaces/API. This is a library that allows you to write C and
Fortran programs that interact with MATLAB. It includes facilities for calling
routines from MATLAB (dynamic linking), calling MATLAB as a
computational engine, and for reading and writing MAT-files.

1-3
1 Introduction

MATLAB Documentation
MATLAB provides extensive documentation, in both printed and online
format, to help you learn about and use all of its features. If you are a new user,
start with this Getting Started book. It covers all the primary MATLAB
features at a high level, including many examples.
The MATLAB online help provides task-oriented and reference information
about MATLAB features. MATLAB documentation is also available in printed
form and in PDF format.

MATLAB Online Help


To view the online documentation, select MATLAB Help from the Help menu
in MATLAB. The MATLAB documentation is organized into these main topics:

• Desktop Tools and Development Environment — Startup and shutdown, the


desktop, and other tools that help you use MATLAB
• Mathematics — Mathematical operations and data analysis
• Programming — The MATLAB language and how to develop MATLAB
applications
• Graphics — Tools and techniques for plotting, graph annotation, printing,
and programming with Handle Graphics®
• 3-D Visualization — Visualizing surface and volume data, transparency, and
viewing and lighting techniques
• Creating Graphical User Interfaces — GUI-building tools and how to write
callback functions
• External Interfaces/API — MEX-files, the MATLAB engine, and interfacing
to Java, COM, and the serial port

MATLAB also includes reference documentation for all MATLAB functions:

• Functions - By Category — Lists all MATLAB functions grouped into


categories
• Handle Graphics Property Browser — Provides easy access to descriptions of
graphics object properties
• External Interfaces/API Reference — Covers those functions used by the
MATLAB external interfaces, providing information on syntax in the calling
language, description, arguments, return values, and examples

1-4
MATLAB Documentation

The MATLAB online documentation also includes

• Examples — An index of examples included in the documentation


• Release Notes — New features and known problems in the current release
• Printable Documentation — PDF versions of the documentation suitable for
printing

For more information about using the Help browser, see Chapter 6, “Desktop
Tools and Development Environment.”

1-5
1 Introduction

Starting and Quitting MATLAB


Starting MATLAB
On Windows platforms, start MATLAB by double-clicking the MATLAB
shortcut icon on your Windows desktop.
On UNIX platforms, start MATLAB by typing matlab at the operating system
prompt.
You can customize MATLAB startup. For example, you can change the
directory in which MATLAB starts or automatically execute MATLAB
statements in a script file named startup.m.

For More Information See “Starting MATLAB” in the Desktop Tools and
Development Environment documentation.

Quitting MATLAB
To end your MATLAB session, select File -> Exit MATLAB in the desktop, or
type quit in the Command Window. You can run a script file named finish.m
each time MATLAB quits that, for example, executes functions to save the
workspace, or displays a quit confirmation dialog box.

For More Information See “Quitting MATLAB” in the Desktop Tools and
Development Environment documentation.

1-6
Starting and Quitting MATLAB

MATLAB Desktop
When you start MATLAB, the MATLAB desktop appears, containing tools
(graphical user interfaces) for managing files, variables, and applications
associated with MATLAB.
The following illustration shows the default desktop. You can customize the
arrangement of tools and documents to suit your needs. For more information
about the desktop tools, see Chapter 6, “Desktop Tools and Development
Environment.”

Enter MATLAB functions at the Command Window prompt.

The Command History maintains a record of


the MATLAB functions you ran.

1-7
MATLAB Tutorial

Chapter 1. Basic MATLAB commands


1.1 Basic scalar operations

First, let's talk about how we add comments (such as this line) to a program. Comments are
lines of text that we want to add to explain what we are doing, so that if we or others read
this code later, it will be easier to figure out what the code is doing. In a MATLAB file, if a
percentage sign, , appears in a row of text, all of the text following the sign is a comment that
MATLAB does not try to interpret as a command. First, let us write a message to the screen to
say that we are beginning to run section 1.1.

The command disp('string') displays the text string to the screen.


disp('Beginning section 1.1 ...')

Next, we set a variable equal to one.


x=1

This command both allocates a space in memory for the variable x, if x has not already been

declared, and then stores the value of 1 in the memory location associated with this variable.

It also writes to the screen "x = 1". Usually, we do not want to clutter the screen with output

such as this, so we can make the command "invisible" by ending it with a semi-colon. As an

example, let us use the following commands to "invisibly" change the value of x to 2 and then

to write out the results to the screen. x=2; this changes the value of x but does not write to

the screen disp('We have changed the value of x.');

Then, we display the value of x by typing "x" without a semi-colon.

Now, let's see how to declare other variables.

y = 2*x; This initializes the value of y to twice that of x

x = x + 1; This increases the value of x by 1.

z = 2*x; This declares another variable z.

z does not equal y because the value of x changed between the

times when we declared each variable.

difference = z - y

Next, we want to see the list of variables that are stored in memory. To do this, we use the
command "who".
who;

We can get more information by using "whos".


whos;

These commands can be used also to get information about only certain variables.
whos z difference;

Let us say we want to get rid of the variable "difference".


We do this using the command "clear".
clear difference;
who;

Next, we want to get rid of the variables x and y.


Again, we use the command "clear".
clear x y;
who;

It is generally good programming style to write only one command per line; however, MATLAB
does let you put multiple commands on a line.
x = 5; y = 13; w = 2*x + y; who;

More commonly one wishes to continue a single command across multiple lines due to the
length of the syntax. This can be accomplished by using three dots.
z = 2*x + ...
y

Finally, when using clear we can get rid of all of the variables at once with the command "clear

all".

clear all;

who; It does not print out anything because there are no variables.

1.2. Basic vector operations

The simplest, but NOT RECOMMENDED, way to declare a variable is by entering the
components one-by-one.
x(1) = 1;

x(2) = 4;

x(3) = 6;

x display contents of x

It is generally better to declare a vector all at once, because then MATLAB knows how much
memory it needs to allocate from the start. For large vectors, this is much more efficient.
y = [1 4 6] does same job as code above

Note that this declares a row vector. To get a column vector, we can either use the transpose
(adjoint for complex x) operator xT = x'; takes the transpose of the real row vector x or, we
can make it a column vector right from the beginning
yT = [1; 4; 6];

To see the difference in the dimensions of a row vs. a column vector, use the command "size"
that returns the dimensions of a vector or matrix.
size(xT)
size(y)
size(yT)
The command length works on both row and column vectors.
length(x), length(xT)

Adding or subtracting two vectors is similar to scalars.


z=x+y
w = xT - yT

Multiplying a vector by a scalar is equally straight-forward.


v = 2*x
c = 4;
v2 = c*x

We can also use the . operator to tell MATLAB to perform a given operation on an element-by-
element basis. Let us say we want to set each value of y such that y(i) = 2*x(i) + z(i)^2 + 1.
We can do this using the code
y = 2.*x + z.^2 + 1
clear x y;
who;

It is generally good programming style to write only one command per line; however, MATLAB
does let you put multiple commands on a line.
x = 5; y = 13; w = 2*x + y; who;

More commonly one wishes to continue a single command across multiple lines due to the
length of the syntax. This can be accomplished by using three dots.
z = 2*x + ...
y

Finally, when using clear we can get rid of all of the variables at once with the command "clear

all".

clear all;

who; It does not print out anything because there are no variables.

1.2. Basic vector operations

The simplest, but NOT RECOMMENDED, way to declare a variable is by entering the
components one-by-one.
x(1) = 1;

x(2) = 4;

x(3) = 6;

x display contents of x

It is generally better to declare a vector all at once, because then MATLAB knows how much
memory it needs to allocate from the start. For large vectors, this is much more efficient.
y = [1 4 6] does same job as code above

Note that this declares a row vector. To get a column vector, we can either use the transpose
(adjoint for complex x) operator xT = x'; takes the transpose of the real row vector x or, we
can make it a column vector right from the beginning
yT = [1; 4; 6];

To see the difference in the dimensions of a row vs. a column vector, use the command "size"
that returns the dimensions of a vector or matrix.
size(xT)
size(y)
size(yT)
The command length works on both row and column vectors.
length(x), length(xT)

Adding or subtracting two vectors is similar to scalars.


z=x+y
w = xT - yT

Multiplying a vector by a scalar is equally straight-forward.


v = 2*x
c = 4;
v2 = c*x

We can also use the . operator to tell MATLAB to perform a given operation on an element-by-
element basis. Let us say we want to set each value of y such that y(i) = 2*x(i) + z(i)^2 + 1.
We can do this using the code
y = 2.*x + z.^2 + 1
The dot and cross products of two vectors are calculated by
dot(x,y)
z=cross(x,y)

We can define a vector also using the notation [a : d : b]. This produces a vector a, a + d, a +
2*d, a + 3*d, ... until we get to an integer n where a + n*d > b. Look at the two examples.
v = [0 : 0.1: 0.5];
v2 = [0 : 0.1: 0.49];

If we want a vector with N evenly spaced points from a to b, we use the command
"linspace(a,b,N)".
v2 = linspace(0,1,5)

Sometimes, we will use a vector later in the program, but want to initialize it at the beginning
to zero and by so doing allocate a block of memory to store it. This is done by
v = linspace(0,0,100)'; allocate memory for column vectors of zero

Finally, we can use integer counting variables to access one or more elements of a matrix.
v2 = [0 : 0.01 : 100];
c=v2(49)
w = v2(65:70)

clear all

1.3. Basic matrix operations

We can declare a matrix and give it a value directly.


A = [1 2 3; 4 5 6; 7 8 9]
We can use commas to separate the elements on a line as well.
B = [1,2,3; 4,5,6; 7,8,9]

We can build a matrix from row vectors


row1 = [1 2 3]; row2 = [4 5 6]; row3 = [7 8 9];
C = [row1; row2; row3]

or from column vectors.


column1 = [1; 4; 7];

column2 = [2; 5; 8];

column3 = [3; 6; 9];

D = [column1 column2 column3]

Several matrices can be joined to create a larger one.


M = [A B; C D]

We can extract row or column vectors from a matrix.


row1 = C(1,:)
column2 = D(:,2)

Or, we make a vector or another matrix by extracting a subset of the elements.


v = M(1:4,1)
w = M(2,2:4)
C = M(1:4,2:5)
The transpose of a real matrix is obtained using the ' operator
D = A'
C, C'

For a complex matrix, ' returns the adjoint (transpose and conjugate. The conjugation
operation is removed by using the "transpose only" command .'
E = D;

E(1,2) = E(1,2) + 3*i;

E(2,1) = E(2,1) - 2*i;

E', E.'

The "who" command lists the matrices in addition to scalar and vector variables.
who

If in addition we want to see the dimensions of each variable, we use the "whos" command.
This tells use the size of each variable and the amount of memory storage that each requires.
whos

The command "size" tells us the size of a matrix.


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

size(M)

num_rows = size(M,1)

num_columns = size(M,2)

Adding, subtracting, and multiplying matrices is straight-forward.


D=A+B
D=A-B
D = A*B

We can declare matrices in a number of ways.

We can create a matrix with m rows and n columns, all containing zeros by
m=3; n=4;
C = zeros(m,n)

If we want to make an N by N square matrix, we only need to use one index.


C = zeros(n)

We create an Identity matrix, where all elements are zero except for those on the principle
diagonal, which are one.
D = eye(5)

Finally, we can use the . operator to perform element-by-element operations just as we did for
vectors. The following command creates a matrix C, such that C(i,j) = 2*A(i,j) + (B(i,j))^2.
C = 2.*A + B.^2

Matrices are cleared from memory along with all other variables.
clear A B
whos
clear all
who
1

SCIENTIFIC COMPUTING
LECTURE # 2
Matrices
2

 Matrices and Magic Squares


 Entering Matrices
 The Transpose

 Subscripts

 The Colon Operator


Matrix
3

 The basic building block of MATLAB is the matrix.


 A matrix is a rectangular array of numbers with m rows and n columns.
 Special matrix is
 Scalars : 1-by-1 matrices.
 Vectors matrices with only one row or column.
Matrix Examples:
4

 Scalar

 Vector

 Array (Matrix)
Matrix size:
5

 The size of A is 1  1
 Size of B is 1  2

 Size of C is 2  2

 Array’s size is (number of rows  number of columns)


Entering Matrices
6

You can enter matrices into MATLAB in several different ways:


• Enter an explicit list of elements.
• Load matrices from external data files.
• Generate matrices using built-in functions.

Entering a list of elements as matrix.


• Separate the elements of a row with blanks or commas.
• Use a semicolon, ; , to indicate the end of each row.
• Surround the entire list of elements with square brackets ,[ ].
Entering Matrices
7

Example:
A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
MATLAB displays:

A is a magic square matrix which take the sum along any column or row, or along either of
the two diagonals, you will always get the same number.
Let us verify that using Matlab: sum(A)
Entering Matrices
8

 Continuation

 The following commands give the same results: A is 3*3 matrix


The Transpose
9

 The transpose operation is denoted by single quote, ‘.


 It flips a matrix about its main diagonal and it turns a row
vector into a column vector. Transpose a matrix
Transpose a row vector
Basic things to keep in mind
10

 Where to type commands:


All MATLAB commands or expressions are entered in the command
window at the MATLAB prompt (» ).
 How to execute commands :

To execute a command or statement , you must press return or enter at


the end.
Subscripts
11

 You can refer to a particular entry in a matrix by using parentheses.


 The element in row i and column j of A is denoted by A(i,j).

For example, A(4,2)


the number in the fourth row and second column.
For matrix A, A(4,2) is 15.
 Lets compute the sum of the elements in the fourth column of A,
type
A(1,4) + A(2,4) + A(3,4) + A(4,4)
This produces
ans = 34
Subscripts
12

Example:

This means that A(2,3) refers to the number 5.


A(3,2) refers to the number 7, which is in the 3rd row, 2nd column.
NOTE:
If you try to use the value of an element outside of the matrix, it is an error:
t = A(4,5)
Index exceeds matrix dimensions.
The Colon Operator
13

 The colon, : , is one of the most important MATLAB operators.


 It occurs in several different forms. It can create vectors, subscript arrays.
The expression 1:10
is a row vector containing the integers from 1 to 10:
1 2 3 4 5 6 7 8 9 10
The expression 100:-7:50
is a row vector containing the integers from 100 to 50 by increment -7:
100 93 86 79 72 65 58 51
The Colon Operator
14

 x = j:k creates a vector x with elements [j,j+1,...,k].


• x = j:i:k creates a regularly vector x using i as increment step
between elements.
• A(:,n) is the nth column of matrix A.
• A(m,:) is the mth row of matrix A.
• A(:) reshapes all elements of A into a single column vector.
The Colon Operator
15

 The colon by itself refers to all the elements in a row or column of a


matrix
 The keyword end refers to the last row or column.

sum(A(:,end))
computes the sum of the elements in the last column of A which is 34
as A is magic matrix.
Test your self
16

 Let:
A =
2 9 -3 10
-4 13 1 6

 Which the value of


 A(2,3) =
 A(1, :) =
 A(:, 3) =
 A(:, 1:2:4) =
 A(: ) =
The magic Function
17

 MATLAB actually has a built-in function that creates magic squares of


almost any size, this function is named magic:
B = magic(4)
B=
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1
Expressions
18

 Like most other programming languages, MATLAB provides mathematical


expressions, but unlike most programming languages, these expressions
involve entire matrices.
 The building blocks of expressions are
❖Variables
❖ Numbers
❖Operators
❖Functions
Variables
19

 MATLAB does not require any type declarations or dimension statements


 When MATLAB encounters a new variable name, it automatically creates the variable and
allocates the appropriate amount of storage.
 If the variable already exists, MATLAB changes its contents and, if necessary, allocates new
storage.
 For example, num_students = 25
❑ creates a 1-by-1 matrix named num_students and stores the value 25 in its single element.

 Variable names consist of a letter, followed by any number of letters, digits, or underscores.
 MATLAB is case sensitive; it distinguishes between uppercase and lowercase letters. A and a
are not the same variable.
 To view the matrix assigned to any variable, simply enter the variable name.
Numbers
20

 MATLAB uses conventional decimal notation, with an optional decimal point


and leading plus or minus sign, for numbers.
 Scientific notation uses the letter e to specify a power-of-ten scale factor.
 Imaginary numbers use either i or j as a suffix
 Some examples of legal numbers are:

 All numbers are stored internally using the long format


Operators
21

 Expressions use familiar arithmetic operators and precedence rules.


Functions
22

 MATLAB provides a large number of standard elementary


mathematical functions, including abs, sqrt, exp, and sin.
 MATLAB also provides many more advanced mathematical
functions, including Bessel and gamma functions.
 Most of these functions accept complex arguments.
 For a list of the elementary mathematical functions, type :
• help elfun
 For a list of more advanced mathematical and matrix functions,
type:
• help specfun
• help elmat
Functions
23

 Some of the functions, like sqrt and sin, are built in.
 Built-in functions are part of the MATLAB core so they are very
efficient, but the computational details are not readily accessible.
Other functions, like gamma and sinh, are implemented in M-files.
 There are some differences between built-in functions and other
functions. For example, for built-in functions, you cannot see the code.
For other functions, you can see the code and even modify it if you
want.
Functions
24

 Several special functions provide values of useful constants.

 The function names are not reserved. It is possible to overwrite any of


them with a new variable,
Working with Matrices
25

 Generating Matrices
 MATLAB provides four functions that generate basic matrices.
Here are some examples:
26
Concatenation
27

o Concatenation is the process of joining small matrices to make bigger


ones. In fact, you made your first matrix by concatenating its individual
elements.
o The pair of square brackets, [], is the concatenation operator.
o For an example, start with the 4-by-4 magic square, A, and form
Concatenation
28

o The result is an 8-by-8 matrix, obtained by joining the four


submatrices:

o sum(B) , Its column sums are the correct value for an 8-by-8 magic
square, result in :
Deleting Rows and Columns
29

➢ You can delete rows and columns from a matrix using just a pair of
square brackets.
➢ Start with
➢ Then, to delete the second column of X, use
➢ This changes X to
Deleting Rows and Columns
30

➢ If you delete a single element from a matrix, the result is not a matrix
anymore. So, expressions like

➢ result in an error. However, using a single subscript deletes a single


element, or sequence of elements, and reshapes the remaining elements
into a row vector. So

➢ Result in :
31

Any Questions
1

SCIENTIFIC COMPUTING
LECTURE # 3
Summary from Previous Week
2

 What Is MATLAB?
◼ MATLAB (MATrix LABoratory)
◼ high-performance language for technical computing
◼ computation, visualization, and programming in an easy-to-use
environment
Summary from Previous Week
3

 Typical uses include:


◼ 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
Why MATLAB
4

 A good choice for vision program development because:


 Easy to do very rapid prototyping
 Quick to learn, and good documentation
 A good library of image processing functions
 Excellent display capabilities
 Widely used for teaching and research in universities and industry
 Another language to impress your boss with !
Why not MATLAB
5

 Has some drawbacks:

 Slow for some kinds of processes


 Not geared to the web

 Not designed for large-scale system development


MATLAB Components
6

 MATLAB consists of:


 The MATLAB language
◼a high-level matrix/array language with control flow statements, functions, data
structures, input/output, and object-oriented programming features.
 The MATLAB working environment
◼ the set of tools and facilities that you work with as the MATLAB user or programmer,
including tools for developing, managing, debugging, and profiling
 Handle Graphics
◼ the
MATLAB graphics system. It includes high-level commands for two-dimensional
and three-dimensional data visualization, image processing, animation, and
presentation graphics
MATLAB Components
7

 The MATLAB function library.


◼a vast collection of computational algorithms ranging from elementary functions like
sum, sine, cosine, and complex arithmetic, to more sophisticated functions like matrix
inverse, matrix eigenvalues, Bessel functions, and fast Fourier transforms as well as
special image processing related functions
 The MATLAB Application Program Interface (API)
◼a library that allows you to write C and Fortran programs that interact with
MATLAB. It include facilities for calling routines from MATLAB (dynamic linking),
calling MATLAB as a computational engine, and for reading and writing MAT-files.
Matrices
8
Matrices
9

 Rows and columns are always numbered starting at 1


 Matlab matrices are of various types to hold different kinds of data
(usually floats or integers)
 A single number is really a 1 x 1 matrix in Matlab!
 Matlab variables are not given a type, and do not need to be
declared
 Any matrix can be assigned to any variable
Matrices
10

 Building matrices with [ ]:

 A = [2 7 4] A = [2 7 4; 3 8 9]

 A = [2; 7; 4] B= [ A A]
Matrices
11

 Building matrices with [ ]:

 A = [2 7 4] A = [2 7 4; 3 8 9]

 A = [2; 7; 4] B= [ A A]
Matrices
12
Matrices
13

 Some operators must be handled with care:


 A = [1 2 ; 4 5]
 B=A*A prints

 B = A .* A prints

 Element by element multiplication


Submatrices
14

 A matrix can be indexed using another matrix, to produce a subset of its elements:
 a = [100 200 300 400 500 600 700] b = [3 5 6]
 c = a(b):
300 500 600
 To get a subsection of a matrix, we can produce the index matrix with the colon
operator:
a (2 : 5)
 Prints: ans= 200 300 400 500
 This works in 2-D as well, e.g. c(2:3, 1:2) produces a 2 x 2 submatrix.
 The rows and columns of the submatrix are renumbered.
Manipulating Matrices
15

 >> A ' % transpose


A=
 >> B*A % matrix multiplication B3= 2 1
1 53 11 0
 >> B.*A % element by element multiplication 4 29 15 7
 >> B/A % matrix division 2 7 2
B=
 >> B./A % element by element division 1 3 1
4 9 5
 >> [B A] % Join matrices (horizontally)
2 7 2
 >> [B; A] % Join matrices (vertically)

◼ Create matrices A and B and try out the matrix operators in this slide
The colon “:” Operator and the function linspace
16
Elementary math functions
17
Elementary math functions
18
19

Any Questions
1

SCIENTIFIC COMPUTING
LECTURE # 6
MATLAB built-in functions
• Introduction
• Mathematical Functions
• Data Analysis Functions
Introduction
 MATLAB has a large number useful of built-in functions
◦ We already saw some examples :
like input, disp, fprintf, zeros, ones

◦ We will cover some in the lecture (mathematical and


statistical)
 More available in the book (Ch 3).
 Very important to know what’s available – READ IT

 We will learn how to write user defined functions

3
Understanding a function call through
an example…..
Computes the
Consider sqrt(100)
square toot of a
number

4
Understanding a function call through
an example…..
Consider sqrt(100)
• The function name is sqrt

5
Understanding a function call through
an example…..
Consider sqrt(100)
• The function name is sqrt

• We give it an argument, 100

6
Understanding a function call through
an example…..
Consider sqrt(100)
• The function name is sqrt

• We give it an argument, 100


• The argument appears between parentheses

7
Understanding a function call through
an example…..
• The argument can be a variable
• And the results can be stored in a variable

>> x = 9;
>> sqrt(x)
ans =
3
>> y = sqrt(x)
y=
3
8
Understanding a function call through
an example…..
• The output of a function call can be the argument of
another function call (nested calls)

>> x = 10000;
Inner function
>> sqrt(sqrt(x)) Outer function call
ans = call
10
>> fprintf(‘square root of %d is %d\n’,x,sqrt(x));
square root of 10000 is 100
9
• sqrt also accepts vectors and matrices as input
• Example:
Sqrt([1, 4, 9])

Can you guess the answer?


Try it on MATLAB

10
Functions that work in a similar manner

• log(x) log10(x) abs(x)


• round(x) floor(x) ceil(x)
• And many more …….

• - Use
• >> help functionName
• to get help about a specific function
• Search MATLAB documentation or textbook index to
find the function you need
• Table at the end of Ch3 is a good reference

11
Example of functions with two parameters
- rem
• rem(x,y) : computes the remainder of the
devision x / y

>> x = 10;
>> rem(x,4)
ans =
2

12
Example of functions with two parameters
- rem
• rem(x,y) : if x is a matrix or vector and y is a
scalar  works like matrix by scalar operators

>> x = [8, 9, 10, 11, 12];


>> rem(x,4)
ans =

0 1 2 3 0

rem(8,4) rem(9,4) rem(12,4)

13
Example of functions with two parameters
- rem
• rem(x,y) : if x is a matrix or vector and y is a
matrix  works like matrix by element by
element operators (ex: .*, ./)
>> x = [8, 9, 10, 11, 12];
>> y = [3, 4, 3, 4, 3];
>> rem(x,y) rem(10,3)

ans =
rem(12,3)
2 1 1 3 0
rem(8,3) rem(9,4)
14
Functions that work in a similar manner

• gcd(x,y) greatest common divisor


• lcm(x,y) lowest common multiplier

15
Data Analysis Functions - through an example

• y = sum(x)
• If x is a vector  y is the sum of elements in
x

>> x = [8, 9, 10];


>> y = sum(x)
y =
27

16
Data Analysis Functions - through an example

• y = sum(x)
• If x is a vector  y is the sum of elements in x
• If x is a matrix  y is the vector of sums of
elements in each column in x
>> x = [8 9 10 ; 20 20 20]; 2 rows
>> y = sum(x)
y = 9+20

28 29 30
10+20
8+20

17
Functions that work in a similar manner

• max min median std var


mode sum

• max and min can be used in other ways

18
More on max and min

• [a,b] = max(x)
• If x is a vector  a is the largest elements in x
• b is the location of a in x

>> x = [8, 9, 10];


>> [a,b] = max(x)
a =
10
b=
3
19
More on max and min

• [a,b] = max(x)
• If x is a matrix  a is the vector containing largest
of element in each column in x
•  b is the location of each element in a

>> x = [8 9 11 ; 7 10 5]; 2 rows


>> [a,b] = max(x)
a =
8 10 11
b =
1 2 1
20
More on max and min

• [a,b] = max(x)
• If x is a matrix  a is the vector containing largest
of element in each column in x
•  b is the location of each element in a

>> x = [8 9 11 ; 7 10 5]; 2 rows


>> [a,b] = max(x)
a =
8 10 11
st
8 is 1 number in column 1
b = 11 is 1st number in column 3

1 2 1
10 is 2nd number in column 2
21
Any Questions
1

SCIENTIFIC COMPUTING
LECTURE # 7
User-defined functions
• Introduction
• M-Files
• Syntax of user-defined functions
• Calling user-defined functions
Introduction
 Functions are M-files that can accept input arguments
and return output arguments.
 The names of the M-file and of the function should be
the same.
 Functions operate on variables within their own
workspace, separate from the workspace you access at the
MATLAB command prompt.

3
M-Files
 M-Files are text files containing MATLAB code.
 Use the MATLAB Editor or another text editor to create a
file containing the same statements you would type at
the MATLAB command line.
 Save the file under a name that ends in .m.

4
M-Files Cont.
There are two kinds of M-files:
1. Scripts

 which do not accept input arguments or return output


arguments.
 They operate on data in the workspace.

2. Functions
 which can accept input arguments and return output
arguments.
 Internal variables are local to the function.

5
M-Files Cont.

6
Script Example
Write the
statements at new
script named
script1.m

7
Script Example Click run to execute
script statements

8
Script Example

The statements are


executed but
nothing appears at
command window

if we type the
variable name the
values appear

9
Syntax of user-defined functions
function returnVar = name ( parameters )
body
end

Names should follow the same


rules as variable names

10
User-defined function(Example)
function volume = boxVolume ( paperW , paperL )
height = 2;
length = paperL – 4;
width = paperW – 4;
volume = length * width * height;
end

11
Function in m-file editor

Matching function name and


File name

12
Function in m-file editor

Function documnetation – will be


displayed if you run the command
>> help boxVolumns

13
Function in m-file editor

Notice that function code does not


start with clear and clc

14
Function in m-file editor
 Some functions
do not return
any output
 Example : A
modified
version of
boxVolume that
calculates and
prints the
volume
There is no output variable and = sign
before the function name

15
Function in m-file editor
 Some functions
return more
than one output
 Example : A
function that
returns all
computed
dimensions in
the box volume
problem

Function returns a vector of variables

16
Calling user-defined functions
 Save it in a file with name same as the function name
ends with .m (Ex. boxVolume.m ).
 Make sure the file is in the current directory or in a
directory on the path.
 Call it from the command line or a script.

17
Calling user-defined functions

This function does not


return value but display
the result

Variable B that will


receive function output

18
Any Questions
SCIENTIFIC COMPUTING
LECTURE # 8
RELATIONAL OPERATORS &
LOGICAL OPERATORS
Relational operators
 A relational operator performs a comparison and returns true or false
(Boolean values)
 Examples
1 > 2  False
(12/4) == 1.5*2  True
 In MATLAB
true is represented as 1
false is represented as 0
Relational Operators in MATLAB

> greater than


>= greater than or equal to
< less than
<= less than or equal to
== equal to
~= not equal to
Example
>> x = 2;
>> y = 10;
>> y/x >= 5
ans =
1
>> y/5 ~= x
ans =
0
Relational operations can be performed on matrices
(element by element)
>> x = [5 6 7; 8 9 10];
>> y = [2 4 6; 8 10 12];
>> z = x >= y
z =
1 1 1
1 0 0
Logical operators
 Logical operators work with Boolean values
 Logical operators in MATLAB:

& and combines 2 result is true if both


conditions conditions are true
| or combines 2 result is true if either
conditions condition is true
~ not negates a result is true if condition
condition is false
and (&) example
>> x = 2; 0 1

>> y = 10;
>> rem(x,5) == 0 & rem(y,5) == 0
ans =
Requires both conditions
to be 1 (true) to give 1
0 (true)
as an answer
and (&) example
>> x = 2;
>> y = 10;
>> rem(x,5) == 0 & rem(y,5) == 0
ans =
0
or (|) example
>> x = 2; 0 1

>> y = 10;
>> rem(x,5) == 0 | rem(y,5) == 0
ans =
Requires at least one
condition to be true to
1 give an true as an
answer
10

Any Questions
SCIENTIFIC COMPUTING
LECTURE # 9
IF STATEMENTS
What’s the use of relational and logical operators?

 Examples:
 Given a set of genes and their expressions, get all
genes with expression higher than a specific level.
 In a pass fail course, give all students with total grade
>= 60 a letter grade P and students with total grade
< 60 a letter grade of F.
 Schedule payday for employees based on the first
letter of their last names.
 Set the room A/C temperature based on the time of the
day.
How to make use of relational and logical
operators?
 Programming constructs /functions that makes use of
relational and logical operators
 if statements
 find function

 loops
Today we will look at selections through
if statements
Input 1 Input 2
______ ______
______ ______
______ ______
______ ______
______ ______
______ ______
______ ______
______ ______
______ ______
The if statement syntax

if condition
commands
end
if statement example
Program LetterGrade

condition
command(s)

>> LetterGrade
Worksapce
if statement example
Program LetterGrade

Red arrow points to


current command

>> LetterGrade
Worksapce
Input your total grade Grade = 85
if statement example
Program LetterGrade

true

>> LetterGrade
Worksapce
Input your total grade 85 Grade =85
grade 85
if statement example
Program LetterGrade

>> LetterGrade
Worksapce
Input your total grade 85 Grade =85
grade 85
Your letter grade is P
if statement example
Program LetterGrade

false

>> LetterGrade
Worksapce
Input your total grade 85 Grade =85
grade 85
Your letter grade is P
if statement example
Program LetterGrade

skip

>> LetterGrade
Worksapce
Input your total grade 85 Grade =85
grade 85
Your letter grade is P
if-else statement example
Program LetterGrade2 : a better version of LetterGrade

>> LetterGrade2
Worksapce
if-else statement example
Program LetterGrade2: a better version of LetterGrade

>> LetterGrade2
Worksapce
Input your total grade Grade = 85
if-else statement example
Program LetterGrade2: a better version of LetterGrade

true

>> LetterGrade2
Worksapce
Input your total grade 85 Grade =85
grade 85
if-else statement example
Program LetterGrade2: a better version of LetterGrade

>> LetterGrade2
Worksapce
Input your total grade 85 Grade =85
grade 85
Your letter grade is P
if-else statement example
Program LetterGrade2: a better version of LetterGrade

No condition to check, i.e. faster code Automatically


skip

>> LetterGrade2
Worksapce
Input your total grade 85 Grade =85
grade 85
Your letter grade is P
if-else statement example
Program LetterGrade2: a better version of LetterGrade

>> LetterGrade2
Worksapce
Input your total grade 85 grade 85
Your letter grade is P
>> LetterGrade2
if-else statement example
Program LetterGrade2: a better version of LetterGrade

>> LetterGrade2
Worksapce
Input your total grade 85 Grade =85
grade 85
Your letter grade is P
>> LetterGrade2
Input your total grade
if-else statement example
Program LetterGrade2: a better version of LetterGrade

false

>> LetterGrade2
Worksapce
Input your total grade 85 Grade =55
grade 85
Your letter grade is P
>> LetterGrade2
Input your total grade 55
if-else statement example
Program LetterGrade2:a better version of LetterGrade

skip

>> LetterGrade2
Worksapce
Input your total grade 85 Grade =55
grade 85
Your letter grade is P
>> LetterGrade2
Input your total grade 55
if-else statement example
Program LetterGrade2: a better version of LetterGrade

>> LetterGrade2
Worksapce
Input your total grade 85 Grade =55
grade 85
Your letter grade is P
>> LetterGrade2
Input your total grade 55
Your letter grade is F
if-else statement example
Program LetterGrade2: a better version of LetterGrade

 What if
 someone entered an invalid input (-ve grade for
example)?
or
 there were more than two cases to cover (you want to
give A, B, C, D, F grades)
if-elseif statement

 What if
 someone entered an invalid input (-ve grade for
example)?
or
 there were more than two cases to cover (you want to
give A, B, C, D, F grades)
General if syntax
if condition1 Every if statement must
consequent1 have if, condition,
elseif condition2 consequent
consequent2
else
alternate
end
General if syntax
if condition1
consequent1
elseif condition2
consequent2
else
alternate
end You can have as many elseif
parts as you need.
General if syntax
if condition1
consequent1
elseif condition2
consequent2
else The final else part is not
alternate necessary, but always a
end good idea.
General if syntax
if condition1
consequent1
elseif condition2
consequent2
else
alternate
end The end word is necessary.
Exercise 1
if (a > b & b > 3) a = 16
c = 3; b = 4

elseif (b > 5) What is the value of c


c = 4; that will be displayed?

else A) 3
c = 5;
B) 4
end;
disp(c) C) 5
Exercise 2
if (a > b & b > 3) a = 3
c = 3; b = 4

elseif (b > 5) What is the value of c


c = 4; that will be displayed?

else A) 3
c = 5;
B) 4
end;
disp(c) C) 5
Exercise 3
if (a > b & b > 3) a = 16
c = 3; b = 4

end What is the value of c


if (b < 5) that will be displayed?

c = 4; A) 3
else
B) 4
c = 5;
end; C) 5

disp(c)
Exercise 4
score = 95
if (score > 55)
disp( ‘D’ ) What will this code
display
elseif (score > 65)
disp( ‘C’) A) D
elseif (score > 80) B) A
disp( ‘B’ )
C) Not good…
elseif (score > 93)
disp( ‘A’ ) What’s wrong with this
else code???
disp( ‘Not good…’ )
end
Exercise 4 - modified
score = 95
if (score > 93)
disp( ‘A’ ) What will this code
display
elseif (score > 80)
disp( ‘B’) A) D
elseif (score > 70) B) A
disp( ‘C’ )
C) Not good…
elseif (score > 60)
disp( ‘D’ )
else
disp( ‘F’ )
end
if statements and vectors
 We know the following

>> X = [70 60 50]


>> X >= 60
ans =
1 1 0
if statements and vectors

 true will not be displayed because the condition is


not true for every element in the vector
 if statements are best fit for scalar values
35

Any Questions
SCIENTIFIC COMPUTING
LECTURE # 10
CHAPTER5 – PART3 FOR LOOPS (5.3)
for loops vs. while loops
2

 In while
we ask MATLAB to execute a block of code while a certain
condition is true
 In for loops
we ask MATLAB to execute a block of code for all values in a
certain vector
Usually used to execute a block of code for a certain number of
times
for loop syntax
3

The template for a for loop is:


for <variable> = <vector>
<code block>
end

How it works:
For each value in <vector>, assign the value to <variable>
and execute the <code block>
Simple for loop example
4

SimpleForLoop

>> SimpleForLoop
Workspace
index 1
Simple for loop example
5

SimpleForLoop

>> SimpleForLoop
Workspace
1 index 1
Simple for loop example
6

SimpleForLoop

>> SimpleForLoop
Workspace
1 index 2
Simple for loop example
7

SimpleForLoop

>> SimpleForLoop
Workspace
1 index 2
2
Simple for loop example
8

SimpleForLoop

>> SimpleForLoop
Workspace
1 index 3
2
Simple for loop example
9

SimpleForLoop

>> SimpleForLoop
Workspace
1 index 3
2
3
Simple for loop example
10

SimpleForLoop

>> SimpleForLoop
Workspace
1 index 4
2
3
Simple for loop example
11

SimpleForLoop

>> SimpleForLoop
Workspace
1 index 4
2
3
4
A for loop can be any of the following
12

for k= [1,3,7,8,9,11]
disp(k) k takes on the values one by one
end

for k = 1:4 Implied increment of 1


disp(k)
Values of k : 1 2 3 4
end

for k = 2:0.5:3
disp(k) real number increment
end Values of k: 2 2.5 3

for k = 0:-2:-7 Negative increment


disp(k) Values of k: 0 -2 -4 -6
end
A for loop can be any of the following
13 Outputs
1
for k= [1,3,7,8,9,11] 3
disp(k) 7
8
end 9
11

for k = 1:4 1
2
disp(k) 3
4
end

for k = 2:0.5:3 2

disp(k) 2.5000
end 3

for k = 0:-2:-7 0
-2
disp(k) -4
-6
end
14
14

 Do we have to use the loop index inside the loop?


No – sometimes it just serves as a counter

Example 2:
A program used in printing flyers that reads a number n
and prints the phrase ‘Welcome Huskies’ n times
Example 2

Write a program, in MATLAB editor, used in printing flyers that reads a


number n from the user and prints the phrase ‘Welcome Huskies’ n times
n = input(‘Enter the number of lines’);
% prints a greeting n times
for k= 1:n
% print the greeting
disp('Welcome Huskies')
end

k is not used in the loop body!


Example 3
16
16

 Write a program in MATLAB editor to Calculate the average of 4 numbers


% Average 4 numbers from user input
n= 4; % number of data values
Initialize your variables
total = 0;
for k= 1:n in which the total will
% read and process input value be accumulated
num= input('Enter a number: ');
total= total + num;
end

avrg = total/n; % average of n numbers


fprintf('Average is %f\n', avrg)
Another way !
17
17

 Write a program, in MATLAB editor to save the values entered by the


user in a vector of values then use the built in function mean() !
 The loop is used to read the values
% Average 4 numbers from user input
n= 4; % initialize the number of data values
numbers = [];
for k= 1:n
% read and save input value
num= input('Enter a number: ');
numbers = [numbers num]
end
avrg = mean(numbers); % average of n numbers
fprintf('Average is %f\n', avrg)
Example 4
18

 Write a program in MATLAB editor, to print a two column table. The


first column is a vector A that consist of numbers between 1 and 10
, and their square roots in the second column. Use fprintf inside a
for loop for better control of the order in which elements are printed.

returns the number of


elements in A

Send the values 2 at a time


Any Questions
SCIENTIFIC COMPUTING
LECTURE # 11
CHAPTER5 – PART3 WHILE LOOPS (5.3)
while loops syntax
2

The template for a for while is:


while <condition>
<code block>
end

How it works:
The <code block> is executed repetitively until the <condition>
becomes false
Simple while loop example
3

SimpleWhileLoop

>> SimpleWhileLoop
Workspace
index 1
Simple while loop example
4

SimpleWhileLoop

true

>> SimpleWhileLoop
Workspace
index 1
Simple while loop example
5

SimpleWhileLoop

>> SimpleWhileLoop
Workspace
1 index 1
Simple while loop example
6

SimpleWhileLoop

>> SimpleWhileLoop
Workspace
1 index 2
Simple while loop example
7

SimpleWhileLoop

true

>> SimpleWhileLoop
Workspace
1 index 2
Simple while loop example
8

SimpleWhileLoop

>> SimpleWhileLoop
Workspace
1 index 2
2
Simple while loop example
9

SimpleWhileLoop

>> SimpleWhileLoop
Workspace
1 index 3
2
Simple while loop example
10

SimpleWhileLoop

true

>> SimpleWhileLoop
Workspace
1 index 3
2
Simple while loop example
11

SimpleWhileLoop

>> SimpleWhileLoop
Workspace
1 index 3
2
3
Simple while loop example
12

SimpleWhileLoop

>> SimpleWhileLoop
Workspace
1 index 4
2
3
Simple while loop example
13

SimpleWhileLoop

true

>> SimpleWhileLoop
Workspace
1 index 4
2
3
Simple while loop example
14

SimpleWhileLoop

>> SimpleWhileLoop
Workspace
1 index 4
2
3
4
Simple while loop example
15

SimpleWhileLoop

>> SimpleWhileLoop
Workspace
1 index 5
2
3
4
Simple while loop example
16

SimpleWhileLoop

false

>> SimpleWhileLoop
Workspace
1 index 5
2
3
4
Simple while loop example
17

SimpleWhileLoop

exit

>> SimpleWhileLoop
Workspace
1 index 5
2
3
4
Example 2: a loop that will not end – infinite loop
18

x = 1; Output
while x ~= 10 1
x = x + 2 3
5
end 7
9

BAD situation!! 11
. . . . .
Loop will never end
Example
19

 Suppose you want to average any set of numbers (not of


known size) entered by the user.

use a while loop!


Average example
20

% This program calculates the average of a series of


% numbers entered by the user
total = 0; % initialize accumulator
count = 0; % initialize count for how many numbers
number = 0; % initialize the control variable

while (number ~= -999) % use -999 as a signal


number = input('enter a number (-999 to end): ');
count = count + 1;
total = total + number;
end
total = total + 999; % -999 was added; remove it
count = count – 1; % removing -999 from the count
avrg = total/count; % calculate the average
fprintf('Average is %f\n', avrg);
21

Any Questions
LECTURE 12
CELL ARRAYS AND FILE INPUT/OUTPUT
Aggregating Strings of unequal length
 We can aggregate strings of unequal length in a cell array.
 A cell array can hold data of non-similar types.
 You reference elements in a cell array using { } instead of ( ).
 Strings of unequal length are one example for that.
Cell Arrays of Strings

>> Y = {'a','bb','ccc‘};

Notice the curly brackets


Cell Arrays of Strings
>> Y = {'a','bb','ccc‘};
>> [rows,columns] = size(Y)
Rows =
1
Columns =
3
It’s not a 2 dimensional
matrix. It’s a vector of three
elements (3 strings)
Cell Arrays of Strings
>> Y = {'a','bb','ccc‘};
>> [rows,columns] = size(Y)
Rows =
1
Columns =
3
>> length(Y{2})
ans =
2
Length of the second string
‘bb’
Cell Arrays of Strings
>> Y = {'a','bb','ccc‘};
>> [rows,columns] = size(Y)
Rows =
1
Columns =
3
>> length(Y{2})
ans =
2
Notice the curly brackets
again
Cell Arrays of Strings
>> Y = {'a','bb','ccc‘};
>> [rows,columns] = size(Y)
Rows =
1
Columns =
3
>> length(Y{2})
ans =
Now, let’s try concatenating
2 ‘zz’ to the first string.
>> Z = [Y{1},’zz’]
Z =
azz
Usage
• We have seen using cell arrays of strings as
labels in a pie charts
>> labels={‘Low Risk',‘Border Line',‘High Risk'};
>> pie(Percentages,labels);
Usage
• We can search for a string in a list of strings
>> Y = {'a','bb','ccc‘};
>> strcmp(Y,’bb’)
ans =
0 1 0
Cell arrays in general…
 Cell arrays can contain other types of data – not only different length
strings
>> MixedArr = {'a',97,[4 5 6]};
>> MixedArr{1}
ans =
a
>> MixedArr{3}
ans =
4 5 6
2-dimensional cell arrays
>> MixedArr = {'a',97,[4 5 6] ; 'c', 'ff', [1]}% 2 rows
MixedArr =
'a' [97] [1x3 double]
'c' 'ff' [ 1]
>> MixedArr{2,2}
ans =
ff
Initializing cell arrays – function cell
 Similar to the zeros and ones functions that enable the
programmer to allocate space in memory for regular matrix, the
cell function allocate space for a cell array

>> CellArr = cell(2,3) columns


CellArr =
rows
[] [] []
[] [] []
empty cells
Usage
 Cell arrays are used to hold data read from an excel file
Reading data from Excel sheets
 To Load data from Excel sheets (spread sheet) use one of the following
commands:
 Only numerical data loaded in a double array
>> numbers = xlsread(‘file.xls');

Matrix name where Matlab function to read


Name of the file to read
numerical data is saved data
 Numerical data and text loaded in a cell array
>> [numbers, text] = xlsread(‘file.xls‘);

Matrix name where Cell array where text


numerical data is saved data is saved
 Numerical data and text and cell array of all data
>> [numbers, text, raw] = xlsread(‘file.xls');
Car’s example cont.
 Consider the following car database, stored in an excel file
Car’s example cont.
 To find the minimum and maximum mileage, we must read the numeric
data in the file
>> num = xlsread('cars.xlsx')
Mileage values is in
num = column 3
2008 20000 43200 2
2011 16600 31700 0
2008 10998 102790 3
2012 15000 34000 2
2013 20500 12023 0
2008 12800 65200 2
2012 52000 18500 0
2011 50000 19000 2
2006 13500 100000 0
2009 25000 40000 1
Car’s example cont.
 Use min and max on column 3 in num
>> mileageColumn = 3;
>> minMileage = min(num(:, mileageColumn))
minMileage =
12023
>> maxMileage = max(num(:, mileageColumn))
maxMileage =
102790
Car’s example cont.
 What if we want to know which car that has the minimum mileage (by
its make and year)?
 In this case we need to read the Make column, which is not numeric
Car’s example cont.
>> [num, txt] = xlsread('cars.xlsx');
>> txt
txt =
'Make' 'Year' 'Cost' 'Miles' 'Accidents‘
'BMW 3 Series' '' '' '' ''
'Volvo Jetta‘ '' '' '' ''
'Volvo Jetta' '' '' '' ''
'Volvo Passat' '' '' '' ''
'Volvo Passat' '' '' '' ''
'Volvo Passat' '' '' '' ''
'BMW X5' '' '' '' ''
'BMW X5' '' '' '' '' Notice that 2 thru 5 columns
were also read because they
'BMW X3' '' '' '' '' contain text in their first row.
'BMW X3' '' '' '' ''
Car’s example cont
 Now we need to find the row that has the minimum mileage on num
 And use it to find the year (in column 1), of the car with minimum
mileage
>> [minMilVal, minMilPos] = min(num(:, mileageColumn))
minMilVal =
12023
minMilPos =
5
>> yearColumn = 1;
>> num(minMilPos,yearColumn)
ans =
2013
Car’s example cont
 We have to do the same thing for the car make.
 Notice that
 Because txt has an additional row (with column titles), the information we
need will be at minMilPos+1
 Also because txt is a cell array, we have to use { }

>> MakeColumInTxt=1;
>> txt{minMilPos+1,MakeColumInTxt}
ans =
Volvo Passat
Car’s example cont.
 xlsread can also return all the data in one cell array. That would be
the third output parameter; raw in the example below.
>>[num, txt, raw] = xlsread('cars.xlsx');
Car’s example cont.
>>[num, txt, raw] = xlsread('cars.xlsx');
>> raw
raw =
{'Make' 'Year' 'Cost' 'Miles' 'Accidents';
'BMW 3 Series' [2008] [20000] [ 43200] [ 2];
'Volvo Jetta' [2011] [16600] [ 31700] [ 0];
'Volvo Jetta' [2008] [10998] [102790] [ 3];
'Volvo Passat' [2012] [15000] [ 34000] [ 2];
'Volvo Passat' [2013] [20500] [ 12023] [ 0];
'Volvo Passat' [2008] [12800] [ 65200] [ 2];
'BMW X5' [2012] [52000] [ 18500] [ 0];
'BMW X5' [2011] [50000] [ 19000] [ 2];
'BMW X3' [2006] [13500] [100000] [ 0];
'BMW X3' [2009] [25000] [ 40000] [ 1]}
Writing to an Excel file
 MATLAB xlswrite write data in a cell array to an Excel file.
 In the car’s example, if we want to update any of the data and write
the data back to a file, the cell array for this data should look like
raw, the cell array returned by xlsread
Summary
 Any program you write involves
 Getting input
 Processing

 Generating output
 Sources of input we covered
 Keyboard
 Excelfile
 Image or sound file

 Sources of output
 Screen
 USB port (Arduino)
 Excel file
 Processing
 Matrix
arithmetic
 MATLAB built in functions
 Mathematical
 Data analysis
 Matrix logical indexing and find function
 Plotting

 Writing user defined functions

 Code flow control


 Ifstatements
 For and while loops

 Strings
28

Any Questions

You might also like