Matlab Workshop Day2_001

download Matlab Workshop Day2_001

of 31

Transcript of Matlab Workshop Day2_001

  • 8/13/2019 Matlab Workshop Day2_001

    1/31

  • 8/13/2019 Matlab Workshop Day2_001

    2/31

    Scripts

    User defined sequence of commands. Scripts in matlab are files terminated with a

    .m extension( thus called M-files)

    M-file : matlab console :: batch files :command prompt

    Matlab functions also written as M-files.

    To create: File->new->scripts/functions OR

    type edit mfilename.m Function syntax- function [output variable

    list]=function name(input argument list)

  • 8/13/2019 Matlab Workshop Day2_001

    3/31

    Some Notes on scripts and

    functions Avoid naming mfiles after inbuilt functions or

    variable names, it creates problems whilecalling.

    Precedence order- variable>nested fn>subfn>current dir fn>inbuilt fn (for those thatwant to know)

    While calling a script/function make sure

    that your current directory(found by typingpwd) is where you saved your m-file or thatyour script directory is added to the matlabscript path.

  • 8/13/2019 Matlab Workshop Day2_001

    4/31

    The function declaration must be the first

    executable line of any MATLAB function.

    For functions the name of the m-file

    should be same as the main function

    name that is mentioned in the 1stline of

    the m-file. For eg. An average function should be

    named as avg.m and first line should

    contain function out=avg(inp)

  • 8/13/2019 Matlab Workshop Day2_001

    5/31

    The variables within the body of the

    function are all local variables.

    Although generally not necessary itsbetter to end a function with an end

    statement( it becomes necessary in

    nested functions) Write a few lines of comments at the

    start of the function body as it appears

    when help for the particular function iscalled and maybe useful later.

  • 8/13/2019 Matlab Workshop Day2_001

    6/31

    An example script

    Lets write a script to plot a sinusoidalwaveform.

    Open script file and start typing

    theta=linspace(0,2*pi,1000);

    plot(theta,sin(theta));%where sin() is an inbuilt functionto generate sin values of data in matrices/array

    Save and close the script file; type thefilename in the console.

  • 8/13/2019 Matlab Workshop Day2_001

    7/31

  • 8/13/2019 Matlab Workshop Day2_001

    8/31

    Functions

    Used to perform predefined action on inputdata.

    function [out1, out2, ...] = fnname(in1, in2, ...)declares the function fnname, and its inputs

    and outputs Subfunctions are functions defined after the

    main function in an mfile. They are visible andusable only by the main function or other

    subfunctions in the mfile. Functions can be called from the console or

    other functions.

  • 8/13/2019 Matlab Workshop Day2_001

    9/31

  • 8/13/2019 Matlab Workshop Day2_001

    10/31

    Popular inbuilt functions

    In matlab console type help elfun andyoull be given a list of elementary built-in

    functions.

    Type help specfun for list of specialinbuilt functions.

    You can click on the hyperlinks in the help

    to see how and where to use each ofthose functions

  • 8/13/2019 Matlab Workshop Day2_001

    11/31

    Varargin, varargout, nargin, nargout

    varargin, varargout used for variableinput/output arguments.

    Similar to elipsis in c.

    Varargin is a cell ( array of arrays just thatarrays need not be of same dimension)

    Nargin and nargout specify the nos. ofinputs and outputs (helps in knowing nosof variable arguments)

    Used as function [out1,out2,varargout]=fn(in1,in2,varargin)

  • 8/13/2019 Matlab Workshop Day2_001

    12/31

    Exercise

    Try writing a script to draw a circle. Hint :you have to use sqrt, hold on, axis square functions; sosee help on what they do.

    Try writing a function to find mean and

    std dev of a sequence. It should havemean and stddev as the 2 outputs and thesequence as an array input.

    Try calling the function as fnname(1:10)and later as [mean,stddev]=fnname(1:10)and see the difference.

  • 8/13/2019 Matlab Workshop Day2_001

    13/31

  • 8/13/2019 Matlab Workshop Day2_001

    14/31

    Signal processing toolbox

    Signal processing toolbox can be used tovisualize signals in time and frequency

    domains, compute FFTs for spectral analysis,

    design FIR and IIR filters, and implementconvolution, modulation, resampling, and

    other signal processing techniques You can

    view and measure signals, design digital

    filters, and analyze spectral windows.

    Overall its a good learning and

    developmental tool for signal processing.

  • 8/13/2019 Matlab Workshop Day2_001

    15/31

    A suite of interactive graphical user

    interfaces(GUI)

    The signal processing toolbox contains verygood GUIs for the following:

    Filter design and analysis

    Window design and analysis Signal plotting and analysis

    Spectral analysis

    Filtering signals

  • 8/13/2019 Matlab Workshop Day2_001

    16/31

    Since MATLAB is a programming language, an endless variety ofdifferent signals is possible. Here are some statements that generate

    several commonly used sequences, including the unit impulse, unit

    step, and unit ramp functions:

    t = (0:0.01:1);

    y = ones(101); % step

    y = [1; zeros(100,1)]; % impulse

    y = t ; % rampy = t.^2; % exponential

    y = square(2*pi*4*t); % generates a square wave every 0.25secs.

    Signal Processing BasicsCommon Sequences

  • 8/13/2019 Matlab Workshop Day2_001

    17/31

    Waveform generat ion

    y = sin(2*pi*50*t) + 2*sin(2*pi*120*t); %two sinusoids,%one at 50 Hz%and one at

    %120Hz with

    %twice the amplitude

    plot(t,y) %plot y versus time

    plot(t(1:50),y(1:50)) %display only the first

    %50 points(zoom!)

  • 8/13/2019 Matlab Workshop Day2_001

    18/31

    Filter Implementation and AnalysisConvolut ion and Fi lter ing

    The mathematical foundation of filtering is convolution. TheMATLAB convfunction performs standard one-dimensionalconvolution, convolving one vector with another

    A digital filter's outputy(k) is related to its inputx(k) byconvolution with its impulse response h(k).

  • 8/13/2019 Matlab Workshop Day2_001

    19/31

    Cont.

    x = [1 2 1];

    h = [1 1 1];

    y = conv(h,x);

    stem(y)

  • 8/13/2019 Matlab Workshop Day2_001

    20/31

    Filters and Transfer Functions

    In general, thez-transform Y(z) of a digital filter's outputy(n) is

    related to thez-transformX(z) of the input by

    where H(z) is the filter's transfer function. Here, the constantsb(i) and a(i) are the filter coefficients and the order of the filteris the maximum of nand m.

    H(z)

  • 8/13/2019 Matlab Workshop Day2_001

    21/31

    Cont.

    For example let;

    step = ones(50); %input data : step function

    b = 1; % Numerator a = [1 -0.9]; % Denominator

    where the vectors b and a represent the coefficients of a filter intransfer function form. To apply this filter to your data, use

    y = filter(b,a,step);

    stem(y)

    fvtool(b,a) %GUI.Dont have to define input (if input is%step/impulse function)%

    19.01

    1)(

    zzH

  • 8/13/2019 Matlab Workshop Day2_001

    22/31

    Images and their toolboxes

    All images in stored in computers are digitalimages, ie. they are sampled and quantized.The samples of an image being called a pixel.

    Greyscale images are 8bit quantized.

    Color images in matlab are commonlyrepresented in 2 methods- rgb and hsv.Overall color images are 3d matrices or 2d

    index matrix with a separate colormap. Videos are treated as a collection of many

    image frames or sampled in time and space.

  • 8/13/2019 Matlab Workshop Day2_001

    23/31

    Image acquisition

    For loading an image we use the imreadcommand.

    Used as img=imread(filename);

    Supports a wide range of file formats,type imformats to see supported formats.

    Try colimg=imread(autumn.tif); and

    grayimg=imread(liftingbody.png);

  • 8/13/2019 Matlab Workshop Day2_001

    24/31

    To display an image we use

    imshow(imgobject);

    To convert between various image typeswe use functions like im2bw,

    rgb2gray,rgb2ind,ind2rgb,rgb2hsv etc.

    Now lets come to actual imageacquisition. For eg. from a camera.

    To acquire camera image we use

    vidobj=videoinput(adaptorname); For windows, camera input is generally in

    winvideo adaptor (videoinput(winvideo))

  • 8/13/2019 Matlab Workshop Day2_001

    25/31

    To view the camera input use

    preview(vidobj)

    To get an image from the camera useimg=getsnapshot(vidobj)

    To get a video stream from the camera

    use vid=getdata(vidobj). Note: nos offrames taken depends on the

    FramesPerTrigger property of vidobj.

    Use implay(vid) to play the video.

  • 8/13/2019 Matlab Workshop Day2_001

    26/31

  • 8/13/2019 Matlab Workshop Day2_001

    27/31

    Image processing toolbox

    To view pixel values in the neighborhood ofa point open the image using imshow andtype impixelregion and move the point usingthe cursor.

    To crop an image use imcrop function. For interactive crop use

    cropimg=imcrop(img) For programmatic crop use

    cropimg=imcrop(img,rect); where rect isarray defining rectangle properties as[xmin,ymin,width,height]

  • 8/13/2019 Matlab Workshop Day2_001

    28/31

    Image can be resized usingnewimg=imresize(old,scale) for aspectlocked scaling or asnewimg=imresize(old,[numrows,numcols]) for general resize.

    To rotate an image use

    rotimg=imrotate(img,angle); where angleis counter clockwise in degrees.

    Imhist(img) is used to display thehistogram of an image. Note: it worksonly on greyscale images or indexed colorimages.

  • 8/13/2019 Matlab Workshop Day2_001

    29/31

    To increase contrast in an image we can

    normalize the histogram using the

    functions histeq(img) or imadjust(im) Regionprops function can be used to

    obtain properties of regions in an image.

    Regionprops can be used for BW orlabeled images only( for BW images it

    generates properties of connected

    components and for labeled imagesgenerates properties for each label).

  • 8/13/2019 Matlab Workshop Day2_001

    30/31

    Regionprops is used as

    stats=regionprops(img,properties); where

    properties is the list of properties youwant.

    Properties that can be returned by

    regionprops can be viewed in its helpdocumentation.

    There are many more interesting

    functions in IP toolbox which can bebetter understood after gaining a good

    base in IP theory.

  • 8/13/2019 Matlab Workshop Day2_001

    31/31

    Other toolboxes

    Other toolboxes can be easily learnt onceyou have a thorough understanding of theconcepts.

    The help documentation in matlab is oneof the best, so use it.

    All help documentation containillustrations at the end.

    Toolboxes come with demos for a fewfamous applications which can also beviewed in help.