1 matlab training
TRANSCRIPT
1. MATLAB Dr. Kashif Mahmood Rajpoot
SEECS, NUST Islamabad [email protected]
NUST Science Society (NSS) Workshop
MATLAB
• MATrix LABoratory • MATLAB
– High-level language – Interactive environment – Enables to perform computationally intensive tasks
faster than with traditional programming languages such 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 of
technical computing – Scientific computing – Numerical analysis – Data visualization – Graphical interface – Symbolic mathematics
• To understand and appreciate the potential of
MATLAB 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 may help
Workshop Teaching Staff
• Workshop instructor – Kashif Mahmood Rajpoot – Email: [email protected]
• 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-in Functions, Scalars, Vectors/Arrays, Matrices, Semi-colon operator (;), Colon operator (:), Basic operations (+, -, /, *, ^, .*/^), Comments, Variable types – string, double, etc, whos command, Variable editor, Various function: linspace, sin, size, Product Help, 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 to Programming and Problem Solving
by Stormy Attaway; 2009 Edition
• MATLAB Programming for Engineers
by 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 a
file), – Calling functions (collection of commands grouped as
a 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 by row and/or column index
Variables and Arrays • Array size (rowXcolumn)
• Number of array elements
• Variable – an identifier for a container that stores 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 any
numerical 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 assignment
statement – var = expression – var = 40; – var2 = var/5; – array = [1 2 3 4]; – x = 1; y=2;
• Expression – a scalar constant, an array, or combination of constants, variables, and mathematical operations
• Important, variable must always be on LHS and expression on RHS – 40 = var??
• An algebraic equality statement vs programming assignment statement – x=x+1;
Initializing variables (cont’d) • Expressions as an array or matrix
• Number of elements in each row and/or column 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 shortcut expressions
– 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 more than one independent variable – E.g., temperature of 5 different locations at 4
different 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 in column major order
– MATLAB allocates 1st column in 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 would return 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 the shape of sub-array
Sub-arrays (cont’d)
• Assigning a scalar to a sub-array
• A scalar value on the RHS replaces all the values indicated by the subscript of the sub-array
Special variables • MATLAB includes a number of pre-defined
values/variables which can be used at any time without initialization
Special variables (cont’d)
• These pre-defined variables are stored as ordinary variable
– Thus, these can be over-written and new values can be assigned to them.
– Be very careful.
Displaying Output Data
• Leaving the semi-colon off
• Default format is used to display the numerical values
– 4 digits after decimal point
– Scientific notation with exponent may be used if number is too large or 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 value of array
– For type char, character string is printed
– Often, string argument to disp is combined with functions num2str, int2str • num2str – convert a number to a string
• int2str – convert an integer to a string
str = *‘The value of pi = ’ num2str(pi)+;
disp(str)
Displaying Output Data • Formatted output display with fprintf function
– A more flexible way to display output data
fprintf(format, data);
• format describes the way the data is to be displayed
• data is the list of one or more scalar/arrays to be displayed
• Conversion characters – Indicate that a value in the data list should be printed out
in 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 always evaluated before expression outside parentheses
• 2^((8+2)/5) ??
Hierarchy/precedence of operations
Array and Matrix Operations • MATLAB supports two types of operations on
arrays
– Array operations
– Matrix operations
Array operations
• Element-by-element basis
• Number of rows and columns must be same
• Array operation can also be performed between 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 values and calculates a single result
– Trigonometric functions
– Square root function
– Log function
– Image manipulation
maxval = 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