Download presentation
Presentation is loading. Please wait.
1
Introduction to MATLAB
CS534 Fall 2015
2
What you'll be learning today
MATLAB basics (debugging, IDE) Operators Matrix indexing Image I/O Image display, plotting A lot of demos ...
3
Who am I Jia-Shen Boon 文嘉绅
4
Who am I
5
Contact Office: 1302CS Office hours: Tuesdays and Thursdays 4:00 - 5:00 p.m., and by appointment
6
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
7
What's great about MATLAB
Matrices are treated as 1st class citizens Effortless to inspect images and plots
8
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
9
Tip #1: Google is your friend.
10
MATLAB basics
11
Your first MATLAB command
Arithmetic operators + - * / Assignment operator = >> total = 1 + 1; 3. Semicolon suppresses output 2. Value from (1) is assigned to this variable 1. MATLAB computes what's 1 + 1
12
MATLAB IDE Current Path COMMAND WINDOW Where you type commands
Workspace List of your current variables Filespace Command History List of previous commands
13
Demo
14
What is a matrix? 5 3 4 3 6 8 1x3 vector 3x1 vector 1 2 3 4 5 6 MxNxP matrix 2x3 matrix Terms: row, column, element, dimension
15
What is a matrix? Second dimension 1 2 3 4 5 6 First dimension
16
What is a matrix? An RGB image is a 3D MxNx3 matrix 236 252 255 24 72
78 An RGB image is a 3D MxNx3 matrix
17
The "layers" in a color image are often called channels
red channel green channel blue channel
18
Expliciting defining a matrix
semicolon separates rows 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);
19
Expliciting defining a matrix (cont'd)
>> A = 1 : 2 : 10 Colon creates regularly spaced vectors start value end value increment
20
Demo
21
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
22
How Operations Work 1 2 3 4 A = 3 1 5 6 B = 4 3 8 10 A+B = -2 1 -2 -2
1 2 3 4 A = 3 1 5 6 B = 4 3 8 10 A+B = -2 1 -2 -2 A-B = 13 13 29 27 A*B = A^2 = A\B = A/B = solves A*x = B solves x*A = B
23
Element-wise operations
1 2 3 4 A = 3 1 5 6 B = A ./ B = 15 24 A .* B = A .^ B =
24
Transpose 9 11 13 15 C = C’ =
25
Demo
26
size() 1 2 3 4 5 6 >> A = [1 2 3; 4 5 6]; >> size(A, 1)
ans = 2 >> size(A, 2) 3 A asks for first dimension asks for second dimension
27
size() cont'd 1 2 3 4 5 6 >> A = [1 2 3; 4 5 6];
>> [height, width] = size(A) height = 2 width = 3 A
28
Matrix indexing 1 2 3 4 5 6 A(2, 3) Element on 2nd row, 3rd column
Note: indexing starts from 1, not zero!
29
Matrix indexing (cont'd)
1 2 3 4 5 6 A(2, :) Returns 2nd row A(:, 3) Returns 3rd column
30
Matrix indexing (cont'd)
1 2 3 4 5 6 >> A = [1 2 3; 4 5 6]; >> A(:, 2:end) ans = Returns concatenation of 2nd, 3rd, …, last column
31
Matrix indexing (cont'd)
1 2 3 4 5 6 >> A = [1 2 3; 4 5 6]; >> A(:, [1 end 1]) ans = Returns concatenation of 1st, last and 1st column
32
Indexing rules apply to 3D matrices too
Element on 2nd row, 4th column of the 3rd channel
33
Logical operators == is equal to
< > <= >= less/greater than ~ not ~= not equal to & logical AND | logical OR && short-circuit AND || short-circuit OR Cover logical indexing?
34
Demo
35
Flow control
36
end keyword Instead of using brackets, MATLAB uses “end” C MATLAB
for(int a=0;a<=10;a++){ if( a>3){ ... … } C for (a=0:10) if (a>3) ... … end MATLAB
37
if/elseif/else if (boolean) … elseif (boolean) else end
Notice elseif is one word
38
while-loop while expression statement end A = 0; while A < 5
disp(A); A = A + 1;
39
for-loop for index = values statements end
Note: for-"condition" overwrites changes to index within the loop!
40
for-loop (cont'd) for A = 1 : 2 : 8 disp(A); end
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;
41
Tip #2: Think in terms of matrices.
42
Logical and linear indexing
Fancier ways to index a matrix.
43
Question: What's the sum of all elements greater than 2 in A?
1 2 3 4 5 6 summation = 0; [height, width] = size(A); for j = 1 : height for i = 1 : width if A(j, i) > 2 summation=summation+A(j, i); end Motivating example for logical indexing
44
Question: What's the sum of all elements greater than 2 in A?
1 2 3 4 5 6 summation = sum( A (A > 2) ); 0 0 1 1 1 1 T Motivating example for logical indexing 22
45
A closer look at sum(A(A>2))
1 2 3 4 5 6 A > 2 returns logical matrix[0 0 1; 1 1 1] A([0 0 1; 1 1 1])returns column vector [ ]' This syntax is known as logical indexing. A, a MxN matrix is indexed by a MxN logical matrix.
46
More examples of logical indexing
Logical indexing on the right-hand side count = sum(2 < A | A == 5); ave = mean(A(mod(A, 2) == 0)); Logical indexing on the left-hand side A(isnan(A)) = 0; count is the sum of elements in A that are less than 2 or are equal to 5. ave is the average of all elements in A that are a multiple of 2. Final example assigns all nan in A to 0.
47
Linear indexing Indexes an element in a matrix with a single number, in column-major order. A(5) A(1) A(3) A = A(6) A(2) A(4)
48
Statistical functions usually return one statistic per column
>> sum(A) ans = >> sum(A(:)) 21
49
List of column-wise statistical functions
sum mean max min median std var ... sum(A, 2) returns row-wise statistics instead
50
Vectorized code tends to be faster than non-vectorized code
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 Using loop: Elapsed time is seconds. 50
51
Vectorized code tends to be faster than non-vectorized code
C = A + B; Elapsed time is seconds. 51
52
MATLAB file types
53
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
54
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
55
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;
56
Matrices are effectively passed into functions "by value"
%my_script.m vector = [ ]; disp(vector) % (1) sort(vector); disp(vector) % same output as (1)
57
Matrices are effectively passed into functions "by value"
%my_corrected_script.m vector = [ ]; sorted_vector = sort(vector);
58
Debugging
59
Before you enter debugging mode
Click this to run program. Program pauses at checkpoints, if there's any. Click along this column to set/remove breakpoints Check this option for the program to pause once an error occurs
60
Debugging mode works like any other IDE
61
Data types
62
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...
63
Be aware of your return types!
imfilter() imread()
64
Be aware of your argument types!
imhist() interp2()
65
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); Answer: interp2 expects im_original to be a single or double but imread returns a logical, uint8 or uint16. Therefore this script will always throw an error.
66
Demo
67
Images
68
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');
69
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
70
Histogram of each channel
71
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!
72
subplot() squeezes more into a figure
subplot(m, n, p); p determines location of this subplot; it's an index in row-major order p is based on an m x n grid 1 2 3 4 5 6
73
Useful MATLAB "hacks"
74
Problem - too many windows
75
Solution - dock figures
set(0, 'DefaultFigureWindowStyle', 'docked')
76
How to time your code tic; % stopwatch starts here
%-- Do some stuff here --% toc; % print time elapsed since tic
77
disp() without newline
%Script disp('newline always included.'); fprintf('No newline here.'); fprintf(' Here is a newline.\n');
78
Reference https://www.google.com/
MATLAB cheat sheet This presentation
79
fin.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.