SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab · 2018-09-06 · SMS 3515:...

11
SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab 2014 Instructor: Nurul Farahain Mohammad 1 It’s all about MATLAB What is MATLAB ? MATLAB is a mathematical and graphical software package with numerical, graphical, and programming capabilities. Figure 1: The logo of MATLAB How MATLAB was started? Cleve Moler, the chairman of the computer science department at the University of New Mexico, started developing MATLAB in the late 1970s. Jack Little, an engineer, was exposed to it during a visit Moler made to Stanford University in 1983. Recognizing its commercial potential, he joined with Moler and Steve Bangert. They rewrote MATLAB in C and founded MathWorks in 1984 to continue its development. Why the name is MATLAB ? It is actually a short form for Matrix Laboratory. What is the strength of MATLAB to be compared to MAPLE or MATHEMATICA ? MATLAB is a very good programme if you are dealing with problems involving matrices, vectors, or any numerical operations. MAPLE and MATHEMATICA are more suitable for symbolic operations. 1

Transcript of SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab · 2018-09-06 · SMS 3515:...

Page 1: SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab · 2018-09-06 · SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab 2014 Instructor: Nurul Farahain

SMS 3515: Scientific Computing

Lecture 1: Introduction to Matlab

2014

Instructor: Nurul Farahain Mohammad

1 It’s all about MATLAB

What is MATLAB ?

MATLAB is a mathematical and graphical software package with numerical, graphical, and programming

capabilities.

Figure 1: The logo of MATLAB

How MATLAB was started?

Cleve Moler, the chairman of the computer science department at the University of New Mexico, started

developing MATLAB in the late 1970s. Jack Little, an engineer, was exposed to it during a visit Moler

made to Stanford University in 1983. Recognizing its commercial potential, he joined with Moler and Steve

Bangert. They rewrote MATLAB in C and founded MathWorks in 1984 to continue its development.

Why the name is MATLAB ?

It is actually a short form for Matrix Laboratory.

What is the strength of MATLAB to be compared to MAPLE or MATHEMATICA ?

MATLAB is a very good programme if you are dealing with problems involving matrices, vectors, or any

numerical operations. MAPLE and MATHEMATICA are more suitable for symbolic operations.

1

Page 2: SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab · 2018-09-06 · SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab 2014 Instructor: Nurul Farahain

2 Love at first sight

Figure 2: MATLAB R2013a running on Linux Ubuntu 14.04

1. Prompt : A symbol that indicate the words written is a command.

2. Command Window : A place where you can write your command. This is also the place where

outputs are shown.

3. Command History : Every command that you wrote in the command prompt will appear here after

the command is executed.

4. Workspace : All computed/called data will be shown here.

5. Current Folder : Shows all folders/files from the path where MATLAB is working.

6. Shows the path of current folder.

7. New Script : By clicking this icon, a new window will be popped out. You can also write your

command there.

2

Page 3: SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab · 2018-09-06 · SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab 2014 Instructor: Nurul Farahain

3 Variables

• Variable is used to store a value in a MATLAB session.

• Assignment statements is used to create variables. Format of this statement:

variablename = expression

• Put ; at the end of your command to suppress the output.

• Default variable uses in MATLAB: ans.

• If a variable is assigned with multiple assignment statements of different values, then it stores the

latest one.

Figure 3: Example of assignment statements and variables

3.1 Initializing, incrementing, and decrementing

• Initializing : assign a value to a variable for the first time.

>> Suarez = 16

Suarez =

3

Page 4: SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab · 2018-09-06 · SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab 2014 Instructor: Nurul Farahain

16

• Incrementing : increase the value of a variable by addition.

>> Suarez = Suarez + 1

Suarez =

17

• Decrementing : decrease the value of a variable by substraction.

>> Suarez = Suarez - 10

Suarez =

7

3.2 Variable / identifier names

These are things that you have to consider in order to name a variable or .m file :

• Must begin with a letter. After that, the name can contain letters, digits, and the underscore character

_ but it cannot have a space. Although underscore characters are valid in a name, their use can cause

problems with some programs that interact with MATLAB, so some programmers use mixed case

instead.

• There is a limit to the length of the name; the built-in function name-lengthmax tells what this

maximum length is.

• Case-sensitive.

• There are certain words called reserved words, or key words, or name of built-in functions that cannot

be used as variable names.

• Meaningful in a way that it can remind you its role that you assign.

Commands related to variables :

• who : shows the name of variables only.

• whos : shows the name of variables together with the assigned values.

• clear : clears out all variables so they no longer exist.

• clear variablename : clears out variable mentioned.

4

Page 5: SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab · 2018-09-06 · SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab 2014 Instructor: Nurul Farahain

4 Expressions

Expressions can be created using values, variables that have already been created, operators, built-in functions,

and parentheses. For numbers, these can include operators such as multiplication, and functions such as

trigonometric functions.

4.1 The format function and ellipsis

• format long : shows outputs in 15 decimal places.

• format short : shows outputs in 4 decimal places.

• format loose : shows outputs with spacing.

• format compact : shows outputs without spacing.

• Continuation operator or ellipsis ... : break a long command into lines.

4.2 Operators

Some commonly used operators for MATLAB programming :

• + : addition.

• − : substraction.

• ∗ : multiplication.

• / : divided by (e.g., 10/5 is 2).

• \ : divided into (e.g., 5\ 10 is 2).

• ∧ : exponentiation. (e.g., 2∧4).

Unlike normal calculator, MATLAB is embedded with operator precedence rules. Somehow, this sometimes

will confuse you because MATLAB didn’t do what you actually want it to compute. In this case, it is

recommended for you to use parantheses (). If the parantheses are nested, the inner parantheses is evaluated

first. The precedence for operators (highest to lowest): parantheses (), exponentiation ∧, negation −, all

multiplication and division ∗, /, \, addition and subtraction +,−.

4.3 Built-in functions and help

You may call these functions from Command Window :

• help : shows list of help topics.

• help topicname : shows list of elementary math functions.

• help functionname : shows description of the function.

5

Page 6: SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab · 2018-09-06 · SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab 2014 Instructor: Nurul Farahain

4.4 Constants

Some functions in MATLAB that return constant values:

• pi : 3.14159.

• i :√−1.

• j :√−1.

• inf : ∞.

• NaN : Not a number such as indeterminate form of 0/0.

4.5 Types / Classes

Types are called classes in MATLAB. Numbers with decimal points can be computed in two types: single

and double (stores larger number than single type. This is also the default type in MATLAB).

Types for integers: int8, int16, int32, int64, uint16, uint32, and uint64. The number after the letter t

represent the bits number while types of integers starting with letter u represent unsigned meaning only

positive integers are involved. One reason for using an integer type for a variable is to save space in memory.

Other types: char for storing characters or strings, and logical for storing true/false values.

4.6 Random numbers

Built-in function rand can be used to generate random numbers in MATLAB. This function generates

number in between 0 and 1. In order to generate random numbers in a bigger range let say 300, you

can multiple the function with 300.

>> rand

ans =

0.8147

>> 300*rand

ans =

271.7376

Random number generators or functions are actually not truly random. Basically, the way it works is that

the process starts with one number, which is called a seed. The seed for the rand function will always be the

same each time MATLAB is started, unless the initial seed is changed. To resolve this issue, you can type

this command

>> rng(’shuffle’)

To generate a random real number in the range from low to high,

6

Page 7: SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab · 2018-09-06 · SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab 2014 Instructor: Nurul Farahain

>> low = 3;

>> high = 5;

>> low + (high -low)*rand

ans =

4.6294

To generate a random integers, let say within 0 - 300,

>> round(300*rand)

The function randn is used to generate normally distributed random real numbers.

5 Characters and encoding

A character in MATLAB is represented using single quotes (e.g., ’a’ or ’x’). The most common character

encoding is the American Standard Code for Information Interchange, or ASCII. Standard ASCII has 128

characters, which have equivalent integer values from 0 to 127. The numeric functions can be used to

convert a character to its equivalent numerical value in different types or classes of MATLAB as discussed

previously. This is also true for strings. On the other hand, the function char does the reverse; it converts

from any number to the equivalent character.

>> double(’a’)

ans =

97

>> char(97)

ans =

a

6 Vectors and Matrices

Vectors and matrices are used to store sets of values, all of which are the same type. A vector can be either a

row vector or a column vector. A matrix can be visualized as a table of values. The dimensions of a matrix

are r × c, where r is the number of rows and c is the number of columns.

7

Page 8: SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab · 2018-09-06 · SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab 2014 Instructor: Nurul Farahain

6.1 Creating row vectors

• By each entries :

>> v = [1 2 3 4]

v =

1 2 3 4

>> v = [1,2,3,4]

v =

1 2 3 4

• By colon operator (e.g. integer starts with 1 and end at 5) :

>> vec = 1:5

vec =

1 2 3 4 5

• By colon operator in the form of (first:step:last) :

>> nv = 1:2:9

nv =

1 3 5 7 9

• By linspace function linspace(x,y,n) where x is starting value, y is terminal value, and n is number of

values generated within the range of x and y :

>> ls = linspace(3,15,5)

ls =

3 6 9 12 15

• By using existing variables (concatenating the vectors) :

>> newvec = [nv ls]

newvec =

1 3 5 7 9 3 6 9 12 15

6.1.1 Referring to and modifying elements

• Access a particular element (e.g. 5th element in newvec) :

>> newvec(5)

ans =

9

8

Page 9: SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab · 2018-09-06 · SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab 2014 Instructor: Nurul Farahain

• Access elements using colon operator :

>> b = newvec(4:6)

b =

7 9 3

• Access elements using index vector (e.g. index vector for 1st, 5th and 10th elements) :

>> newvec([1 5 10])

ans =

1 9 15

• Change the value stored in a vector element (e.g. change 2nd element of vector b) :

>> b(2) = 11

b =

7 11 3

6.2 Creating column vectors

• By using semicolons :

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

c =

1

2

3

4

• By transposing a row vector :

>> r = 1:4;

>> c = r’

c =

1

2

3

4

9

Page 10: SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab · 2018-09-06 · SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab 2014 Instructor: Nurul Farahain

6.3 Creating matrix variables

The values within a row are separated by either spaces or commas, and the different rows are separated by

semicolons. There must always be the same number of values in each row.

>> mat = [4 3 1; 2 5 6]

mat =

4 3 1

2 5 6

• Random matrix :

rand(n) generates a random matrix of size n × n (n rows and n columns) while rand(r,c) generates a

random matrix of size r × c (r rows and n columns).

• Zero matrix :

zeros(n) generates a zero matrix of size n × n (n rows and n columns) while zeros(r,c) generates a zero

matrix of size r × c (r rows and n columns).

• Matrix of all ones :

ones(n) generates a matrix of all ones of n × n (n rows and n columns) while ones(r,c) generates a

matrix of all ones of size r × c (r rows and n columns).

• Transpose matrix :

Put single quote ’ after a vectorname.

• Empty vector :

Can be created using empty square brackets [ ]. This vector is useful to remove / delete elements.

You can also access and/or change any elements in a matrix by giving the number of row/s and number of

column/s in parantheses, just like how you learned with vectors.

6.4 Dimensions

• length(vectorname) : shows the number of elements in a vector.

• length(matrixname) : shows the number of rows or columns in a matrix, whichever is largest.

• size(matrixname) : shows the number of rows, and then number of columns.

• numel(matrixname) : shows the total number of elements in any array. For vectors, this is equivalent

to the length of the vector. For matrices, it is the product of the number of rows and columns.

• end : can be used in row and/or column indexes to refer to the last row/column.

• reshape(mat,r,c) : reshaping matrix mat into a r × c matrix. It iterates through the matrix columnwise.

• fliplr(matrixname) : flips the matrix from left to right (in other words, the left-most column which is

the first column, becomes the last column and so forth).

10

Page 11: SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab · 2018-09-06 · SMS 3515: Scientific Computing Lecture 1: Introduction to Matlab 2014 Instructor: Nurul Farahain

• flipud(matrixname) : flips up to down.

• rot90(matrixname) : rotates the matrix counterclockwise 90 degrees.

• repmat(mat,m,n) : creates a larger matrix that consists of an m × n matrix of copies of matrix mat

(replicate mat).

6.5 Three-dimensional matrices

For a three-dimensional matrix, imagine a two-dimensional matrix as being flat on a page, and then the

third dimension consists of more pages on top of that one (so, they are stacked on top of each other). In

MATLAB, it is just as simple as having another index.

>> mat = ones(4)

mat =

1 1 1 1

1 1 1 1

1 1 1 1

1 1 1 1

>> mit = 5*ones(4)

mit =

5 5 5 5

5 5 5 5

5 5 5 5

5 5 5 5

>> mat(:,:,2) = mit

mat(:,:,1) =

1 1 1 1

1 1 1 1

1 1 1 1

1 1 1 1

mat(:,:,2) =

5 5 5 5

5 5 5 5

5 5 5 5

5 5 5 5

11