• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
1   matlab training

1 matlab training






Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

    1   matlab training 1 matlab training Presentation Transcript

    • 1. MATLABDr. Kashif Mahmood RajpootSEECS, NUST Islamabadkashif.rajpoot@seecs.edu.pkNUST Science Society (NSS) Workshop
    • MATLAB• MATrix LABoratory• MATLAB– High-level language– Interactive environment– Enables to perform computationally intensive tasksfaster than with traditional programming languagessuch as C, C++, and Fortran• Numerical computing environment• Plotting (i.e. visualization) of functions and data• Algorithm implementation• User interfaces• Rapid prototyping, with toolboxes
    • MATLAB Demos• MATLAB– Basic Matrix Operations– Matrix Manipulations• Curve Fitting– Introduction to spline fitting: gridded data• Fuzzy Logic– Fuzzy C-means clustering• Image Processing– Registering an Image Using Normalized Cross-Correlation– Detecting a cell using image segmentation• Neural Network• Parallel Computing
    • MATLAB Demos• Partial Differential Equation– pdedemos: wave equation, heat equation• Signal Processing• Symbolic Math– Calculus• Wavelet– Image fusion– wavemenu
    • MATLAB Advantages• “Fourth-generation” programming language• Ease of use• Platform independence• Predefined functions• Device-independent plotting• Graphical user interface• MATLAB compiler
    • Workshop Learning Goals• To get familiar with MATLAB: the language oftechnical computing– Scientific computing– Numerical analysis– Data visualization– Graphical interface– Symbolic mathematics• To understand and appreciate the potential ofMATLAB programming
    • Workshop Design• Four lectures (3.50 hours)–Two 1-hour each lectures–Two 45-minutes each lectures• Four hands-on sessions (2 hours)–Four 30-minutes each hands-on sessions–PRACTICE–Competition
    • Workshop Design (cont’d)• Status– Introductory• Audience– Engineer/Scientist/Mathematician and others• Pre-requisites– Basic understanding of computers– Some understanding of programming mayhelp
    • Workshop Teaching Staff• Workshop instructor– Kashif Mahmood Rajpoot– Email: kashif.rajpoot@seecs.edu.pk• Workshop assistant– Atif Riaz– Ammara Nasim
    • Workshop Contents: Session 1• Introduction to MATLAB• MATLAB Basics: Command Window, Editor,Workspace, Command History,Editing/Opening/Saving File• Programming Basics: Variables, Commands, Built-inFunctions, Scalars, Vectors/Arrays, Matrices, Semi-colon operator (;), Colon operator (:), Basicoperations (+, -, /, *, ^, .*/^), Comments, Variabletypes – string, double, etc, whos command, Variableeditor, Various function: linspace, sin, size, ProductHelp, fprintf, disp, str2num, num2str, isempty,isnumeric
    • Workshop Contents: Session 2• Cell and Structure Arrays• Plotting: 2D plots – legend, title, xlabel, ylabel,subplot, stem, barh, comet, area, imagesc, etc.3D plots – surf, mesh• Symbolic Math
    • Workshop Contents: Session 3• Conditions: if, else• Loops: for, while• Vectorization• Function: input/output arguments, saving,opening file, naming, calling function
    • Workshop Contents: Session 4• GUI: Controls, static element, axes, menus,callbacks, hObject, eventdata, handles,figures, GUIDE, Property Inspector, guidata,dialog boxes• Simulink• Conclusion
    • MATLAB Texts• MATLAB: A Practical Introduction toProgramming and Problem Solvingby Stormy Attaway; 2009 Edition• MATLAB Programming for Engineersby Stephen Chapman; 2nd Edition
    • MATLAB Basics• MATLAB environment– Command window– Command history window– Edit window– Figure window– Workspace browser/Variable editor– Help browser– Current directory browser– Work directory
    • MATLAB Command Window• Command execution– Calculations,– Expressions,– Assignments,– Calling scripts (collection of commands stored in afile),– Calling functions (collection of commands grouped asa reusable sub-routine),– etc.• MATLAB as a scratchpad– E.g., area or volume of the cylinder (A=πr2, V=Al)
    • MATLAB Environment• MATLAB command history window– History of the previous commands executed• Edit window– Create/modify m-files• Figure window– Display MATLAB graphics output• Workspace browser– View/edit workspace contents– “whos”• Help window
    • MATLAB Basics• Useful commands– help– ↑ up-arrow– → Tab-completion• MATLAB search path– The Path Tool (GUI)
    • Arrays• Array – fundamental unit of data in MATLAB– Collection of data values organized into rows and columns• Vectors or matrices– Vector is 1-dimensional (row or column vector)– Matrix is 2- or higher-dimensional• Individual elements are accessed by array name followed byrow and/or column index
    • Variables and Arrays• Array size (rowXcolumn)• Number of array elements• Variable – an identifier for a container thatstores some data value• Variable naming rules– Begin with alphabet letter, followed by letter,number or underscore– 31 character length, case sensitive• Assign meaningful and descriptive names– E.g., year, day, grade, exchange_rate
    • Variable types/classes• double (single, double)– double is automatically created for storing anynumerical value• char• integer (int8, uint8, int16, uint16, int32,uint32)• string (array of chars)• Weakly typed vs strongly typed languages
    • Initializing variables• Assign data to the variable in an assignmentstatement– var = expression– var = 40;– var2 = var/5;– array = [1 2 3 4];– x = 1; y=2;• Expression – a scalar constant, an array, orcombination of constants, variables, andmathematical operations• Important, variable must always be on LHS andexpression on RHS– 40 = var??• An algebraic equality statement vs programmingassignment statement– x=x+1;
    • Initializing variables (cont’d)• Expressions as an array or matrix• Number of elements in each row and/orcolumn of matrix must be same
    • Initializing variables (cont’d)• Examples of arrays• Semi-colon at the end of statement– Suppresses echoing/displaying the value– Quick debugging or program testing tool– Speeds the program execution
    • Initializing variables (cont’d)• Initializing variables with shortcutexpressions– x=1:2:10– angle = -pi:.01:pi– g=1:4;– h=*g’ g’+;• Transpose operator
    • Initializing variables (cont’d)• Initializing variables with built-in functions
    • Initializing variables (cont’d)• Initializing variables with keyboard input– Prompt a user and take input from keyboard– my_val = input(‘Enter an input value : ’);– Scalar input– Vector/matrix input (enclosed in brackets)– Empty matrix as input• Character string as input– in = input(‘Enter data : ’, ‘s’);– Enter data : 1.23– Stores string ‘1.23’ into variable in
    • Multi-dimensional Arrays• To represent data which are functions of morethan one independent variable– E.g., temperature of 5 different locations at 4different times• Higher dimensions– c(:,:,1)=[1 2 3;4 5 6];– c(:,:,2)=[7 8 9;10 11 12];• Colon (:) operator– Access all the elements
    • Multi-dimensional Arrays in Memory• 2-d array (matrix) is stored incolumn major order– MATLAB allocates 1st columnin memory, then 2nd,and so on..
    • Sub-arrays• Subset of an array• The end Function– Special function to access the last subscript of an array– arr = [1 2 3 4; 5 6 7 8; 9 10 11 12];– arr(2:end, 2:end)– First end would return 3, while second end wouldreturn 4
    • Sub-arrays (cont’d)• Sub-array on LHS of an assignment statement– To update only a subset of an array– Shape of values being assigned must match theshape of sub-array
    • Sub-arrays (cont’d)• Assigning a scalar to a sub-array• A scalar value on the RHS replaces all thevalues indicated by the subscript of the sub-array
    • Special variables• MATLAB includes a number of pre-definedvalues/variables which can be used at anytime without initialization
    • Special variables (cont’d)• These pre-defined variables are stored asordinary variable– Thus, these can be over-written and new valuescan be assigned to them.– Be very careful.
    • Displaying Output Data• Leaving the semi-colon off• Default format is used to displaythe numerical values– 4 digits after decimal point– Scientific notation with exponentmay be used if number is too largeor too small• The default format can be changed
    • Displaying Output Data• The disp function– Another way to display output/data– Accepts array argument/input and displays the valueof array– For type char, character string is printed– Often, string argument to disp is combined withfunctions num2str, int2str• num2str – convert a number to a string• int2str – convert an integer to a stringstr = *‘The value of pi = ’ num2str(pi)+;disp(str)
    • Displaying Output Data• Formatted output display with fprintf function– A more flexible way to display output datafprintf(format, data);• format describes the way the data is to be displayed• data is the list of one or more scalar/arrays to bedisplayed• Conversion characters– Indicate that a value in the data list should be printed outin the desired format• Escape characters– n indicates a line feed (new line)
    • Displaying Output Data• Common conversion/escape characters
    • Scalar Operations• Standard arithmetic operations• Expression inside parentheses are alwaysevaluated before expression outsideparentheses• 2^((8+2)/5) ??
    • Hierarchy/precedence of operations
    • Array and Matrix Operations• MATLAB supports two types of operations onarrays– Array operations– Matrix operations
    • Array operations• Element-by-element basis• Number of rows and columns must be same• Array operation can also be performedbetween an array and a scalar
    • Matrix operations• Follow normal rules of linear algebra• Matrix operations vs array operations• Differentiate by . operator• .*, ./, etc.
    • Data Files• Load and save data in files on the storage device• save– Save data from MATLAB workspace into file– Save filename var1 var2 var3;– .mat file extension– No variable specified• MAT file format– Stores variable name, type, size and values– Portable between different platforms– Not readable by other programs
    • Data Files (Cont’d)• Load/read data from file– load filename• Loading all/selected variables from file
    • Built-in MATLAB Functions• Function – accepts one or more input valuesand calculates a single result– Trigonometric functions– Square root function– Log function– Image manipulationmaxval = max([1 -5 6 -3])[maxval, index] = max([1 -5 6 -3])
    • Built-in MATLAB Functions (Cont’d)• MATLAB functions with array inputs– sin(x)– Ease and simplicity of scalar/array input• Common MATLAB functions– sqrt– floor– ceil– exp– num2str