1 matlab training

51
1. MATLAB Dr. Kashif Mahmood Rajpoot SEECS, NUST Islamabad [email protected] NUST Science Society (NSS) Workshop

Upload: waleed-usman

Post on 07-May-2015

351 views

Category:

Technology


3 download

TRANSCRIPT

Page 1: 1   matlab training

1. MATLAB Dr. Kashif Mahmood Rajpoot

SEECS, NUST Islamabad [email protected]

NUST Science Society (NSS) Workshop

Page 2: 1   matlab training

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

Page 3: 1   matlab training

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

Page 4: 1   matlab training

MATLAB Demos

• Partial Differential Equation – pdedemos: wave equation, heat equation

• Signal Processing

• Symbolic Math – Calculus

• Wavelet – Image fusion

– wavemenu

Page 5: 1   matlab training

MATLAB Advantages

• “Fourth-generation” programming language

• Ease of use

• Platform independence

• Predefined functions

• Device-independent plotting

• Graphical user interface

• MATLAB compiler

Page 6: 1   matlab training

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

Page 7: 1   matlab training

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

Page 8: 1   matlab training

Workshop Design (cont’d)

• Status – Introductory

• Audience – Engineer/Scientist/Mathematician and others

• Pre-requisites – Basic understanding of computers

– Some understanding of programming may help

Page 9: 1   matlab training

Workshop Teaching Staff

• Workshop instructor – Kashif Mahmood Rajpoot – Email: [email protected]

• Workshop assistant

– Atif Riaz – Ammara Nasim

Page 10: 1   matlab training

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

Page 11: 1   matlab training

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

Page 12: 1   matlab training

Workshop Contents: Session 3

• Conditions: if, else

• Loops: for, while

• Vectorization

• Function: input/output arguments, saving, opening file, naming, calling function

Page 13: 1   matlab training

Workshop Contents: Session 4

• GUI: Controls, static element, axes, menus, callbacks, hObject, eventdata, handles, figures, GUIDE, Property Inspector, guidata, dialog boxes

• Simulink

• Conclusion

Page 14: 1   matlab training

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

Page 15: 1   matlab training

MATLAB Basics • MATLAB environment

– Command window

– Command history window

– Edit window

– Figure window

– Workspace browser/Variable editor

– Help browser

– Current directory browser

– Work directory

Page 16: 1   matlab training

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)

Page 17: 1   matlab training

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

Page 18: 1   matlab training

MATLAB Basics

• Useful commands

– help

– ↑ up-arrow

– → Tab-completion

• MATLAB search path

– The Path Tool (GUI)

Page 19: 1   matlab training

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

Page 20: 1   matlab training

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

Page 21: 1   matlab training

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

Page 22: 1   matlab training

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;

Page 23: 1   matlab training

Initializing variables (cont’d) • Expressions as an array or matrix

• Number of elements in each row and/or column of matrix must be same

Page 24: 1   matlab training

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

Page 25: 1   matlab training

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

Page 26: 1   matlab training

Initializing variables (cont’d)

• Initializing variables with built-in functions

Page 27: 1   matlab training

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

Page 28: 1   matlab training

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

Page 29: 1   matlab training

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..

Page 30: 1   matlab training

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

Page 31: 1   matlab training

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

Page 32: 1   matlab training

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

Page 33: 1   matlab training

Special variables • MATLAB includes a number of pre-defined

values/variables which can be used at any time without initialization

Page 34: 1   matlab training

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.

Page 35: 1   matlab training

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

Page 36: 1   matlab training
Page 37: 1   matlab training

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)

Page 38: 1   matlab training

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)

Page 39: 1   matlab training

Displaying Output Data

• Common conversion/escape characters

Page 40: 1   matlab training

Scalar Operations • Standard arithmetic operations

• Expression inside parentheses are always evaluated before expression outside parentheses

• 2^((8+2)/5) ??

Page 41: 1   matlab training

Hierarchy/precedence of operations

Page 42: 1   matlab training

Array and Matrix Operations • MATLAB supports two types of operations on

arrays

– Array operations

– Matrix operations

Page 43: 1   matlab training

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

Page 44: 1   matlab training

Matrix operations • Follow normal rules of linear algebra

• Matrix operations vs array operations

• Differentiate by . operator

• .*, ./, etc.

Page 45: 1   matlab training
Page 46: 1   matlab training

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

Page 47: 1   matlab training

Data Files (Cont’d) • Load/read data from file

– load filename

• Loading all/selected variables from file

Page 48: 1   matlab training

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])

Page 49: 1   matlab training

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

Page 50: 1   matlab training
Page 51: 1   matlab training