introduction to matlab - university of...

17
9/15/2015 1 Introduction to MATLAB CS 534 Fall 2015 What you'll be learning today MATLAB basics (debugging, IDE) Operators Matrix indexing Image I/O Image display, plotting A lot of demos ... Who am I Jia-Shen Boon 文嘉Who am I

Upload: lamkhanh

Post on 26-Jun-2018

247 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

1

Introduction to MATLAB

CS 534 Fall 2015

What you'll be learning today

● MATLAB basics (debugging, IDE)

● Operators

● Matrix indexing

● Image I/O

● Image display, plotting

● A lot of demos

● ...

Who am I

Jia-Shen Boon 文嘉绅

Who am I

Page 2: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

2

Contact

Office: 1302CS

E-mail: [email protected]

Office hours: Tuesdays and Thursdays 4:00 -

5:00 p.m., and by appointment

Accessing MATLAB

Get a local copy from the Campus Software

Library

Also available in the Linux and Windows labs

Also remotely accessible via ssh

On Linux, type matlab into the terminal

What's great about MATLAB

Matrices are treated as 1st class citizens

Effortless to inspect images and plots

What's not so great about MATLAB

Data structures besides matrices can feel like

2nd class citizens

Proprietary ($$)

Syntax sometimes not as elegant as other

dynamically typed languages

Page 3: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

3

Tip #1:

Google is your friend. MATLAB basics

Your first MATLAB command

Arithmetic operators + - * /

Assignment operator =

>> total = 1 + 1;

1. MATLAB computes what's 1 + 1 2. Value from (1) is assigned to this

variable

3. Semicolon suppresses output

MATLAB IDE

COMMAND WINDOW

Where you type

commands

Workspace

List of your

current

variables

Command History

List of previous

commands

Current

Path

Filespace

Page 4: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

4

Demo

What is a matrix?

5

3

4

3 6 8

1 2 3

4 5 6

3x1 vector

1x3 vector

2x3 matrix

MxNxP matrix

Terms: row, column, element, dimension

What is a matrix?

1 2 3

4 5 6

Fir

st dim

ensio

n

Second dimension

What is a matrix?

24 72

78

236 252 255

An RGB image is a 3D MxNx3 matrix

Page 5: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

5

The "layers" in a color image are

often called channels

red channel blue channel green channel

Expliciting defining a matrix

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

A =

1 2 3

4 5 6

Bonus: you can define a matrix using other matrices too! What's the output of the following? a = [1 2]; b = [a 3 4]; c = [5 6 a; b]; disp(c);

semicolon separates rows

Expliciting defining a matrix (cont'd)

>> A = 1 : 5

A =

1 2 3 4 5

>> A = 1 : 2 : 10

A =

1 3 5 7 9

Colon creates regularly spaced vectors

increment

start value end value

Demo

Page 6: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

6

More arithmetic operators

+ Addition

- Subtraction

* Matrix Multiplication

^ Matrix Power

' Transpose

\ Left Matrix Division (Solves A*x=B)

/ Right Matrix Division (Solves x*A=B)

.* Element by Element Multiplication

./ Element by Element Division

.^ Element by Element Power

How Operations Work

3 1

5 6 B =

1 2

3 4 A =

4 3

8 10 A+B =

-2 1

-2 -2 A-B =

13 13

29 27 A*B =

7 10

15 22 A^2 =

solves A*x = B -.3077 .3846

.1538 .6923 A/B = -1 4

2 1.5 A\B = solves x*A = B

Element-wise operations

3 2

15 24 A .* B =

.333 2

.6 .666 A ./ B =

1 2

243 4096 A .^ B =

3 1

5 6 B =

1 2

3 4 A =

Transpose

1 3

5 7

9 11

13 15

C =

1 5 9 13

3 7 11 15

C’ =

Page 7: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

7

Demo

size()

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

>> size(A, 1)

ans =

2

>> size(A, 2)

ans =

3

1 2 3

4 5 6

A

asks for first dimension

asks for second dimension

size() cont'd

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

>> [height, width] = size(A)

height =

2

width =

3

1 2 3

4 5 6

A

Matrix indexing

A(2, 3)

Element on 2nd row, 3rd column

Note: indexing starts from 1, not zero!

1 2 3

4 5 6

Page 8: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

8

Matrix indexing (cont'd)

A(2, :)

Returns 2nd row

A(:, 3)

Returns 3rd column

1 2 3

4 5 6 Matrix indexing (cont'd)

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

>> A(:, 2:end)

ans =

2 3

5 6

Returns concatenation of 2nd, 3rd, …, last

column

1 2 3

4 5 6

Matrix indexing (cont'd)

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

>> A(:, [1 end 1])

ans =

1 3 1

4 6 4

Returns concatenation of 1st, last and 1st

column

1 2 3

4 5 6

Bonus: there's other ways to index a MATLAB matrix! Google 'linear indexing MATLAB' or 'logical

indexing MATLAB'!

Indexing rules apply to 3D matrices

too

A(2, 4, 3)

Element on 2nd row, 4th column of the 3rd

channel

1 4 2 8

3 7 9 1

4 5 6 3

Page 9: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

9

== is equal to

< > <= >= less/greater than

~ not

~= not equal to

& logical AND

| logical OR

&& short-circuit AND

|| short-circuit OR

Logical operators

Flow control

Instead of using brackets, MATLAB uses “end”

end keyword

for(int a=0;a<=10;a++){

if( a>3){

...

}

}

C

for (a=0:10)

if (a>3)

...

end

end

MATLAB

if/elseif/else

if (boolean)

elseif (boolean)

else

end

Notice elseif is one word

Page 10: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

10

while-loop

while expression

statement

end

A = 0;

while A < 5

disp(A);

A = A + 1;

end

for index = values

statements

end

Note: for-"condition" overwrites changes to

index within the loop!

for-loop

for A = 1 : 2 : 8

disp(A);

end

for-loop (cont'd)

Bonus: values can be a 2D matrix too! What is the output of the following?

for A = [1 2 3; 4 5 6]; disp(A); end;

Tip #2:

Think in terms of

matrices.

Page 11: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

11

Time Cost Comparison

• Loop vs. No Loop

A = rand(1000,1000);B = rand(1000,1000);

for i = 1:size(A,1),

for j = 1:size(A,2),

C(i,j) = A(i,j) + B(i,j);

end

end

Using loop: Elapsed time is 1.125289 seconds.

Time Cost Comparison(cont.)

• Loop vs. no loop

C = A + B

Elapsed time is 0.002346 seconds.

Try to take advantage of matrix/vector

structure whenever possible

MATLAB file types

There's two types of .m files

●Matlab code is saved in .m files

●Function .m files ○ Contain a function definition

○ One function per file

○ FILE NAME MUST MATCH FUNCTION NAME

●Script .m files ○ Contain a list of commands

○ Can be named anything

○ Often used as drivers for functions you have

implemented

○ Kind of like main in other languages

Page 12: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

12

Writing MATLAB functions

● Structure of a MATLAB function

● Functions Can Return Multiple values

● Make sure you initialize your return variables

function returnVal = FunctionName (input1,input2)

%Adds two numbers

returnVal = input1+input2;

end

function [return1, return2] = FunctionName (input1,input2)

return1 = input1+input2;

return2= 0;

end

How do these two files behave

differently?

%average1.m

total = x + y;

average = total / 2;

%average2.m

function average = average2(x, y)

total = x + y;

average = total / 2;

Matrices are effectively passed into

functions "by value"

%my_script.m

vector = [6 3 2 5 4 1];

disp(vector) % (1)

sort(vector);

disp(vector) % same output as (1)

Debugging

Page 13: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

13

Click along this column

to set/remove

breakpoints

Check this option for

the program to pause

once an error occurs

Click this to run

program. Program

pauses at checkpoints,

if there's any.

Before you enter debugging mode

Debugging mode works like any

other IDE

Data types

Important data types

logical true/false

uint8 8-bit unsigned integer

double 64-bit double-precision floating point

single 32-bit single-precision floating point

There's also uint16, uint32, int8, int16...

Page 14: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

14

Be aware of your return types!

imread()

imfilter()

Be aware of your argument types!

interp2()

imhist()

Is there anything wrong with this

script?

im_original = imread('lena_gray.jpg');

[Xq, Yq] = meshgrid(0.5:99.5, 0.5:99.5);

im_interp = interp2(im_original, Xq, Yq);

Demo

Page 15: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

15

Images

Generic image processing script

filename = 'badgers.jpg';

im_orig = imread(filename);

im_processed = my_func(im_orig);

figure; imshow(im_orig);

figure; imshow(im_processed);

imwrite(im_processed, 'hw.jpg');

Important image related functions

imread Read image from disk

imwrite Write image to disk

figure Create new figure

imshow Display image

im2double Convert image datatype to

double im2uint8 Convert image datatype to

uint8

Histogram of each channel

Page 16: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

16

Histogram of each channel

im = imread('badgers.jpg');

for channel = 1:3

subplot(2, 3, channel);

imshow(im(:, :, channel));

subplot(2, 3, channel + 3);

imhist(im(:, :, channel));

end

imhist expects a 2D matrix!

subplot() squeezes more into a

figure

subplot(m, n, p);

1

4

2

5

3

6

p is based on an m x n grid

p determines location of this subplot;

it's an index in row-major order

Useful MATLAB "hacks"

Problem - too many windows

Page 17: Introduction to MATLAB - University of …pages.cs.wisc.edu/~dyer/cs534-spring09/slides/matlab/matlab...Introduction to MATLAB ... indexing MATLAB'! Indexing rules apply to 3D matrices

9/15/2015

17

Solution - dock figures

set(0, 'DefaultFigureWindowStyle', 'docked')

How to time your code

tic; % stopwatch starts here

%-- Do some stuff here --%

toc; % print time elapsed since tic

disp() without newline

%Script

disp('newline always included.');

fprintf('No newline here.');

fprintf(' Here is a newline.\n');

Reference

https://www.google.com/

https://courses.engr.illinois.edu/cs445/fa2015/le

ctures/Useful%20Functions%20in%20Matlab.p

df MATLAB cheat sheet

https://goo.gl/AZBlCh This presentation