CS 534 Fall 201 5 What youll be learning today MATLAB b asics debugging IDE Operators Matrix indexing Image IO Image display plotting A lot of demos Who am I JiaShen Boon ID: 720318
Download Presentation The PPT/PDF document "Introduction t o MATLAB" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Introduction to MATLAB
CS 534
Fall
201
5Slide2
What you'll be learning today
MATLAB b
asics (debugging, IDE
)
Operators
Matrix indexing
Image I/O
Image display, plotting
A lot of demos
...Slide3
Who am IJia-Shen Boon
文嘉绅Slide4
Who am ISlide5
ContactOffice: 1302CSE-mail: boon@cs.wisc.eduOffice hours: Tuesdays and Thursdays 4:00 - 5:00 p.m., and by appointmentSlide6
Accessing MATLAB
Get a local copy from the
Campus Software Library
Also available in
the Linux and Windows labs
Also
remotely access
i
ble via
ssh
On Linux, type
matlab
into the terminalSlide7
What's great about MATLABMatrices are treated as 1st class citizensEffortless to inspect images and plotsSlide8
What's not so great about MATLABData structures besides matrices can feel like 2nd class citizensProprietary ($$)
Syntax sometimes not as elegant as other dynamically typed languagesSlide9
Tip #1:Google is your friend.Slide10
MATLAB basicsSlide11
Your first MATLAB commandArithmetic 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 outputSlide12
MATLAB IDE
COMMAND WINDOW
Where you type commands
Workspace
List of your current variables
Command History
List of previous commands
Current Path
FilespaceSlide13
DemoSlide14
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
,
dimensionSlide15
What is a matrix?
1 2 3
4 5 6
First dimension
Second dimensionSlide16
What is a matrix?
24
72
78
236
252
255
An RGB image is a 3D MxNx3 matrixSlide17
The "layers" in a color image are often called
channels
red channel
blue channel
green channelSlide18
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 rowsSlide19
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 valueSlide20
DemoSlide21
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 PowerSlide22
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 = BSlide23
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 =Slide24
Transpose
1 3
5 7
9 11
13 15
C =
1 5 9 13
3 7 11 15
C’ =Slide25
DemoSlide26
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 dimensionSlide27
size() cont'd>> A = [1 2 3; 4 5 6];
>> [height, width] = size(A)
height =
2
width =
3
1 2 3
4 5 6
ASlide28
Matrix indexingA(2, 3)Element on 2nd row, 3rd column
Note: indexing starts from 1, not zero!
1 2 3
4 5 6Slide29
Matrix indexing (cont'd)A(2, :)Returns 2nd row
A(:, 3)
Returns 3rd column
1 2 3
4 5 6Slide30
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 6Slide31
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'!Slide32
Indexing rules apply to 3D matrices tooA(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 Slide33
==
is equal to
<
>
<=
>=
less/greater than
~
not
~=
not equal to
&
logical AND
|
logical OR
&&
short-circuit AND
||
short-circuit OR
Logical operatorsSlide34
Flow controlSlide35
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
MATLABSlide36
if/elseif/else
if (boolean)
…
elseif (boolean)
…
else
…
end
Notice
elseif
is one wordSlide37
while-loop
while
expression
statement
end
A = 0;
while A < 5
disp(A);
A = A + 1;
endSlide38
for index = values
statements
end
Note:
for-
"condition" overwrites changes to
index
within the loop!
for
-loopSlide39
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;Slide40
Tip #2:Think in terms of matrices.Slide41
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.Slide42
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 possibleSlide43
MATLAB file typesSlide44
There's two types of .m filesMatlab 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 languagesSlide45
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;
endSlide46
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;Slide47
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)Slide48
DebuggingSlide49
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 modeSlide50
Debugging mode works like any other IDESlide51
Data typesSlide52
Important data typeslogical 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
...Slide53
Be aware of your return types!
imread()
imfilter()Slide54
Be aware of your argument types!
interp2()
imhist()Slide55
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);Slide56
DemoSlide57
ImagesSlide58
Generic image processing scriptfilename = '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');Slide59
Important image related functionsimread 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 uint8Slide60
Histogram of each channelSlide61
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!Slide62
subplot() squeezes more into a figuresubplot(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 orderSlide63
Useful MATLAB "hacks"Slide64
Problem - too many windowsSlide65
Solution - dock figuresset(0, 'DefaultFigureWindowStyle', 'docked')Slide66
How to time your codetic; % stopwatch starts here
%-- Do some stuff here --%
toc; % print time elapsed since ticSlide67
disp() without newline
%Script
disp('newline always included.');
fprintf('No newline here.');
fprintf(' Here is a newline.\n');Slide68
Referencehttps://www.google.com/
https://courses.engr.illinois.edu/cs445/fa2015/lectures/Useful%20Functions%20in%20Matlab.pdf
MATLAB cheat sheet
https://goo.gl/AZBlCh
This presentation