Matlab Tutorial.

Slides:



Advertisements
Similar presentations
StatLab Workshop Yale University Maximiliano Appendino, Economics October 18 th, 2013.
Advertisements

Introduction to MATLAB The language of Technical Computing.
Matlab Tutorial. Session 1 Basics, Filters, Color Space, Derivatives, Pyramids, Optical Flow Gonzalo Vaca-Castano.
Introduction to Matlab
1 EMT 101 – Engineering Programming Dr. Farzad Ismail School of Aerospace Engineering Universiti Sains Malaysia Nibong Tebal Pulau Pinang Week 10.
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
MATLAB – What is it? Computing environment / programming language Tool for manipulating matrices Many applications, you just need to get some numbers in.
Image Processing in Matlab An Introductory Approach by Sabih D. Khan
Introduction to MATLAB and image processing. MATLAB and images The help in MATLAB is very good, use it! An image in MATLAB is treated as a matrix Every.
MATLAB for Image Processing April 10 th, Outline Introduction to MATLAB –Basics & Examples Image Processing with MATLAB –Basics & Examples.
1 Introduction to MatLab: Image Processing - MatLab stands for Matrix Laboratory. - Most of the programming operations have as input or output a matrix.
1 Introduction to MatLab MatLab stands for Matrix Laboratory. As the name suggests most of the programming operations have as input or output a matrix.
Concatenation MATLAB lets you construct a new vector by concatenating other vectors: – A = [B C D... X Y Z] where the individual items in the brackets.
C ENTER FOR I NTEGRATED R ESEARCH C OMPUTING MATLAB
Introduction to Array The fundamental unit of data in any MATLAB program is the array. 1. An array is a collection of data values organized into rows and.
What is MATLAB ? MATrix LABratory –Originally, it was a front-end to FORTRAN matrix routines developed in the U. of New Mexico and Stanford –Today.
Chapter 10 Review: Matrix Algebra
Chapter 5. Loops are common in most programming languages Plus side: Are very fast (in other languages) & easy to understand Negative side: Require a.
Matlab tutorial course Lesson 2: Arrays and data types
Martin Ellison University of Warwick and CEPR Bank of England, December 2005 Introduction to MATLAB.
Nonparametric Econometrics1 Intro to Matlab for Data Analysis and Statistical Modeling.
Introduction to MatLab: Image Processing
Introduction to MATLAB adapted from Dr. Rolf Lakaemper.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
Eng Ship Structures 1 Introduction to Matlab.
INTRODUCTION TO MATLAB LAB# 01
Gulsah Tumuklu Ozyer MATLAB IMAGE PROCESSING TOOLBOX.
Matlab Basics Tutorial. Vectors Let's start off by creating something simple, like a vector. Enter each element of the vector (separated by a space) between.
Introduction to MATLAB adapted from Dr. Rolf Lakaemper.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Computer Simulation Lab Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz “Lecture 2”
Matlab & LaTeX Tutorial Course web page: vision.cis.udel.edu/cv February 14, 2003  Lecture 2.
Digital Image Processing Lecture 6: Introduction to M- function Programming.
Digital Image Processing Introduction to M-function Programming.
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
CIS 601 Fall 2003 Introduction to MATLAB Longin Jan Latecki Based on the lectures of Rolf Lakaemper and David Young.
Digital Image Processing Introduction to MATLAB. Background on MATLAB (Definition) MATLAB is a high-performance language for technical computing. The.
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
Intro to Matlab Rogelio Long September 3, How to access MyDesktop Log in with your utep id and password.
Manipulating MATLAB Vector, Matrices 1. Variables and Arrays What are variables? You name the variables (as the programmer) and assign them numerical.
CIS 595 MATLAB First Impressions. MATLAB This introduction will give Some basic ideas Main advantages and drawbacks compared to other languages.
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
Intro To MATLAB CS Fall 2013 Zach Welch. Overview ●Basics ●MATLAB data structures ●Operations ●Useful functions ●Image Processing and other useful.
Tutorial on Matlab Basics
Matlab Training Session 4: Control, Flow and Functions
Statistical Computing in MATLAB
Some Matlab Tips CSE 4309 – Machine Learning Vassilis Athitsos
Introduction to MATLAB
Scripts & Functions Scripts and functions are contained in .m-files
MATLAB DENC 2533 ECADD LAB 9.
Matlab Workshop 9/22/2018.
Introduction to MatLab: Image Processing
Introduction to MATLAB
StatLab Matlab Workshop
MATH 493 Introduction to MATLAB
Use of Mathematics using Technology (Maltlab)
StatLab Workshop: Intro to Matlab for Data Analysis and Statistical Modeling 11/29/2018.
Matlab tutorial course
Vectorized Code, Logical Indexing
INTRODUCTION TO MATLAB
MATLAB Programming Basics Copyright © Software Carpentry 2011
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Midterm Exam Closed book, notes, computer Similar to test 1 in format:
Introduction to MATLAB
Announcements P3 due today
Simulation And Modeling
MATLAB stands for MATrix LABoratory.
Matlab Basics Tutorial
Matlab Basics.
Presentation transcript:

Matlab Tutorial

Matrices

Matrices

Matrices 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

Images and Matrices How to build a matrix (or image)? 4 5 6 7 8 9 >> B = zeros(3,3) B = 0 0 0 0 0 0 >> C = ones(3,3) C = 1 1 1 1 1 1 >>imshow(A) (imshow(A,[]) to get automatic pixel range)

Building Matrices Building matrices with [ ]: A = [2 7 4] B = [ A A ] 2 7 4 2 7 4 2 7 4 3 8 9 ? 2 7 4 2 7 4 3 8 9 3 8 9

Operating on whole Matrices

Special matrix operators Some operators must be handled with care: A = [1 2 ; 4 5] B = A * A prints 9 12 24 33 B = A .* A prints 1 4 16 25 Element by element multiplication

Submatrices 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

Submatrices 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. a = [100 200 300 400 500 600 700]

loops ‘for’ loops in MATLAB iterate over matrix elements: b = 0 for i = [ 3 9 17] b = b + i; end Result: 29 Note: The MATLAB way to write that program would have been: b = sum([ 3 9 17]); Avoid loops if possible !

loops The typical ‘for’ loop looks like: for i = 1:6 … end Which is the same as: for i = [1 2 3 4 5 6]

Famous Matrix Manipulation Algorithms Singular value decomposition---[U,S,V]=svd(A) Eigenvalues and eigenvectors---[V,D] = eig(A) Orthogonal-triangular decomposition- [Q,R]=qr(A) LU factorization --[L,U] = lu(A) Matrix rank -- a=rank(A) Condition number -- a=cond(A) Linear systems: A\b solves A*x = b

Constructing Matrices Basic built-ins: All zeroes, ones: zeros, ones Identity: eye Random: rand (uniform), randn (unit normal) Ranges: m:n, m:i:n (i is step size) Composing big matrices out of small matrix blocks repmat(A, m, n): “Tile” a big matrix with m x n copies of A

Manipulations & Calculations on matrices Transpose (‘), inverse (inv) Matrix arithmetic: +, -, *, /, ^ Elementwise arithmetic: .*, ./, .^ Functions Vectorized sin, cos, etc.

Deconstructing Matrices Indexing individual entries by row, col: A(1, 1) is upper-left entry Ranges: e.g., A(1:10, 3), A(:, 1) Matrix to vector and vice versa by column: B = A(:), A(:) = B Transpose to use row order find: Indices of non-zero elements

Control Structures

Control Structures Expressions, relations (==, >, |, &, functions, etc.) if/while expression statements end Use comma to separate expression from statements if on same line if a == b & isprime(n), M = inv(K); else M = K; end for variable = expression statements end for i=1:2:100, s = s / 10; end

function [c,d,e]= pyt(a,b) % returns the hypotenuse in a right angle % triangle according to Pythagoras theorem. % c is the hypotenuse, % d and e are the two sharp angles c=sqrt(a.^2+b.^2); d=atan(b./a); e=pi/2-d;

if: if (A > B), statement; if i==1, elseif (A< B), statement; elseif ~A, statement; else, end if i==1, statement; end if res(n,2) ~= 0, else,

switch switch (rem(n,3) ==0) & (rem(n,2)==0) case 0 disp('n is not dividable by 6') case 1 disp('n is dividable by 6') otherwise error('This is impossible.') end

for for n=1:1:4, subplot(2,2,n) plot(a(:,1),a(:,n+1)) title(num2str(n)) end

while a = 4; fa = sin(a); b = 2; fb = sin(b); while a - b > 5 * eps, x = (a+b)/2; fx = sin(x); if sign(fx) == sign(fa), a = x; fa=fx; break; else b = x; fb = fx; end

Plotting 2-D vectors: plot(x, y) 3-D: plot3(x, y, z)(space curve) plot(0:0.01:2*pi, sin(0:0.01:2*pi)) 3-D: plot3(x, y, z)(space curve) Surfaces meshgrid makes surface from axes, mesh plots it [X,Y] = meshgrid(-2:.2:2, -2:.2:2); Z = X .* exp(-X.^2 - Y.^2); mesh(Z) surf: Solid version of mesh Saving figures, plots: print –depsc2 filename

Miscellaneous Diary: Recording a session diary filename diary off tic, toc bracketing code to measure execution time

Once again: AVOID LOOPS

Logical Conditions equal (==) , less than and greater than (< and >), not equal (~=) and not (~) find(‘condition’) - Returns indexes of A’s elements that satisfies the condition. >> [row col]=find(A==7) row = 3 col = 1 >> [row col]=find(A>7) 3 col = 2 >> Indx=find(A<5) Indx = 1 2 4 7 A = 2 3 5 6 7 8 9

Flow Control A = 1 2 0 2 1 2 0 2 1 Flow control in MATLAB - if, else and elseif statements (row=1,2,3 col=1,2,3) if row==col A(row, col)=1; elseif abs(row-col)==1 A(row, col)=2; else A(row, col)=0; end A = 1 2 0 2 1 2 0 2 1

Flow Control A = 1 2 0 2 1 2 0 2 1 Flow control in MATLAB - for loops for row=1:3 for col=1:3 if row==col A(row, col)=1; elseif abs(row-col)==1 A(row, col)=2; else A(row, col)=0; end A = 1 2 0 2 1 2 0 2 1

Flow Control while, expression, statements, end Indx=1; while A(Indx)<6 A(Indx)=0; Indx=Indx+1; end A = 2 3 5 6 7 8 9 A = 0 2 3 0 5 6 7 8 9

M-Files Any text file ending in “.m” Use path or addpath to tell Matlab where code is (non-persistent?) Script: Collection of command line statements Function: Take argument(s), return value(s). First line defines: function y = foo(A) function [x, y] = foo2(a, M, N) Comment: Start line with %

Working with M-Files M-files can be scripts that simply execute a series of MATLAB statements, or they can be functions that also accept input arguments and produce output. MATLAB functions: Are useful for extending the MATLAB language for your application. Can accept input arguments and return output arguments. Store variables in a workspace internal to the function.

Working with M-Files Create a new empty m-file function B=test(I) [row col]=size(I) for r=1:row for c=1:col if r==c A(r, c)=1; elseif abs(r-c)==1 A(r, c)=2; else A(r, c)=0; end B=A;

Composition of MATLAB

Examples Try these MATRIX AND VECTOR OPERATIONS This is how we can define a vector >> v=[1, 2, 3] Matlab prints out the following v =     1     2     3 Similarly we can define a matrix >> M= [ 1 2 3; 4 5 6; 7 8 9] The result is: M =     1     2     3     4     5     6     7     8     9 If you want to suppress the MatLab output then you need to finish the line with semicolon as follows. >>M= [ 1 2 3; 4 5 6; 7 8 9];

Projection Say you want to extract some rows and columns of a matrix. This is called a projection. We simply give the subset of rows and columns as parameters, as follows >> M11=M(2:3 , 2:3) M11 = 5 6 8 9 To specify all elements in a given dimension one can use ':‘ So to get all rows but just columns 1 and 2, we type >> A= M( :, 1:2) A = 1 2 4 5 7 8

WORKING WITH IMAGES in MatLab Let’s talk about image files and their formats….. Color vs GrayScale Basic Image Processing functions: Reading in an image: >> img1=imread('Water lilies.jpg'); Displaying an image: >> imshow(img1); Finding out size of an image: >> size(img1); >> size(img1) ans = 600 800 3 imread imshow size

variable imgsmall WORKING WITH IMAGES in MatLab Cropping an image: >> imgsmall=img1(200:300,300:400,1:3); >> imshow(imgsmall) >> imgsmall=img1(150:250,350:450,1:3); >> size(imgsmall) ans = 101 101 3 Exercise: 1. Find 2 images online 2. Crop them to the same size 3. Add the two images together. 4. Display resulting image Advanced Exercise: Rescale images to same size then add them See next slide to see HOWTO rescale variable imgsmall

ReScaling linspace round We can rescale by changing the number of rows and columns, yet preserve the information in the image >> [rows, cols, colors]= size(img1) rows = 600 cols = 800 colors = 3 % Increase the number of rows >> stretchfactor = 1.5 >> rowVec= linspace(1,rows,stretchfactor*rows); >> newrows=round(rowVec); >> newimag=img1(newrows,:,:) >> imshow(newimg); % Decrease number of columns >> stretchfactor = 0.75; >> colVec= linspace(1,cols,stretchfactor*cols); >> newcols=round(colVec); >> newimag=newimg(:,newcols,:) >>imshow(newimg) linspace round

Example Program: Inverting an image To invert or to add two images we need to convert to double and then rescale the result back so that it looks like an image InvImg= 1 - double(IMG1)/255; NewImg = uint8(round(InvImg*255))) Imshow(NewImg); uint8

input WORKING WITH IMAGES in MatLab Color Masking Sometimes we want to replace pixels of an image of one or more colors with pixels from another image. It is useful to use a “blue or green screen” in some instances. Find an image with a big plot of one color. First we will replace that color. And then we will find another image for pixel replacement. Let us plot the color values of one chosen row…This will tell us the pixel values of the color we want to replace. v = imread(‘myimg.jpg’) image(v) row= input(‘which row?’); red = v(row,:,1); green = v(row,:,2); blue = v(row,:,3); plot(red,’r’); hold on plot(green,’g’); plot(blue,’b’); input

WORKING WITH IMAGES in MatLab Suppose we want to replace those values whose intensities exceed a threshold value of 160 in each color. v= imread(‘myimg.jpg’); thresh= 160 layer = (v(:,:,1) > thresh) & (v(:,:,2) > thresh) (v(:,:,2) > thresh) mask(:,:,1) = layer; mask(:,:,2) = layer; mask(:,:,3) = layer; If you want to only mask a portion of the image you can use something like… >> mask(700:end,:,:)= false; Which sets the mask so that we do not affect rows 700 and above To reset the color to red >>newv = v; >>newv(mask)(1) = 255 Or to replace pixels from a different image w use… >> newv(mask) = w(mask); Let us try to do this with a blue screen…..

Histograms

Image reading and showing imread imshow

Image Histogram imhist

Histogram Equalization histeq

Noise

Adding Noise Filtering Noise imnoise medfilt2

Add Image to noise

Median Filtering removes noise

Median Filtering removes Gaussian noise imnoise fspecial imfliter

FSPECIAL creates special 2D filters

Imfilter – multidimensional filtering

Thresholding

Thresholding

IM2BW – converting to binary by thresholding

Repeated thresholding

Separating background by thresholding

Feature Extraction Extracting features: Corner Center point

Edge Detection

Example of kernel-based filtering - Sobel Edge Detection edge Example of kernel-based filtering - Sobel

Edge, Sobel and Prewitt

Roberts, Laplacian, Zero-cross, Canny edge detection methods

Use of threshold in Sobel affects what is found

“Laplacian of Gaussian” filtering is often better

Canny Filter is even better – this is a major invention with many applications in robotics. Can one invent a better one?

Edge Detection with gray and binary images Many variants of combining thresholding and edge detection exist

EDGE DETECTION IN MATLAB

Hough Transform

Hough Transform Hough Transform has links to Fourier, Radon and Neural Nets. A deep concept

Camera Calibration

Calibration of Cameras Matrix/vector multiplication

Sequences of operations

Noise, filtering and histogramming

Fourier Transform in MATLAB

Other data MATLAB can also handle Movies 3D objects …

Sources Rolf Lakaemper Fred Annexstein Jason Rife Hyunki Lee Amin Allalou www.cis.udel.edu/~cer/arv