What is MATLAB? Introduction to MATLAB

Introduction to MATLAB 1 What is MATLAB? A software environment for interactive numerical calculations MATrix LABoratory: Based on matrices computat...
0 downloads 3 Views 865KB Size
Introduction to MATLAB

1

What is MATLAB? A software environment for interactive numerical calculations MATrix LABoratory: Based on matrices computations standard for numerical simulations Examples:         

Linearly Algebra Solving nonlinear equations Numerical solution of differential equations Mathematical optimization Statistics and data analysis Signal processing Modeling of dynamic system Solving partial differential equations Simulation of Systems Engineering Computational Intelligence, CI 2015

Introduction to MATLAB

2

Why do we need MATLAB? MATLAB use:  implementation of simple learning algorithms  evaluate the results / data visualization Using toolboxes:  Training of neural networks: pattern matching for face detection of hidden  Markov models: for example for speech processing

Computational Intelligence, CI 2015

Introduction to MATLAB

3

Alternative/Similar software • GNU Octave (https://www.gnu.org/software/octave/ )

• Can run most MATLAB scripts but not all! • Doesn’t have the same “toolboxes” • Python/numpy (http://www.numpy.org/ )

• Different syntax, but easier if you’re already familiar with python syntax • more flexible because one can use other standard python libraries also • Julia (http://julialang.org/ )

• Very new, not very popular yet • Looks promising, has an impressive list of features

Computational Intelligence, CI 2015

Introduction to MATLAB

4

Structure Core functionality: compiled C routines Most functionality is given by m-files, grouped into toolboxes 

  

m-files contain source code, can be copied and changed m-files are platform independent (PC, Unix / Linux, MAC) Interpreted language which makes it well suited for prototyping / debugging! :) But slow! :(

Contr. Syst.

Sig. Proc.

C-kernel

m-files

Neural Networks Computational Intelligence, CI 2015

Introduction to MATLAB

5

The help system Search for matching functions >> lookfor keyword

Quick help with syntax and function definition >> help function

Advanced hyperlinked help system is started by >> Helpdesk

Online: http://www.mathworks.com/help/

Computational Intelligence, CI 2015

Introduction to MATLAB

6

Interactive calculations MATLAB is interactive. There are no variable declarations required >> 2 + 3 * 4/2 ans = 8

>> A = 5e-3; b = 1; a + b; 

Variables are created automatically and are not bound to any type



Variable names are case-sensitive

Most mathematical functions and constants are already defined >> Cos (pi) >> Abs (1 + i)

Computational Intelligence, CI 2015

Introduction to MATLAB

7

Variables and memory management MATLAB uses double precision >> format long >> pi ans = 3.141592653589793 >> format short >> pi ans = 3.1416

Computational Intelligence, CI 2015

Introduction to MATLAB

8

Variables and memory management All variables in the "Workspace" are indicated by >> who >> whos Variables can be stored in .mat files

>> save filename a b >> clear a b

% clear all variables for from workspace

>> load filename a b

Computational Intelligence, CI 2015

Introduction to MATLAB

9

Vectors and matrices Vectors (arrays) are defined as: >> V = [1, 2, 4, 5] >> W = [1; 2; 4; 5]

Matrices (2D arrays) are defined >> A = [1,2,3; 4,-5,6; 5,-6,7]

Ascending list of numbers using ":" Operator >> X = 1: 5

>> X = 1: 2: 5

Computational Intelligence, CI 2015

Introduction to MATLAB

10

Matrix Operators All common operators are overloaded >> V + 2

Usual operators are available >> B = A’ % Complex Conjugate Transpose >> A * B >> A + B

Note:  Operators that begin with a point (.) always use each item individually in the matrices. >> A .* B

% elementwise multiplication

>> A .^ 2

% elementwise Square Computational Intelligence, CI 2015

Introduction to MATLAB

11

Indexing matrices Indexing is by brackets >> A (2,3)

1. Index: line 2. Index: Column ... Or partial matrices by Row and column index. >> A ([2 3], [1 2])

Order of the indices is important! >> B = A ([3: 2], [2 1])

>> B = [A (3,2), A (3,1), A (2,2), A (2,1)]

Access to the latest index >> A (end, 2) Computational Intelligence, CI 2015

Introduction to MATLAB

12

Indexing matrices Indexing all the rows or Columns by “:” Operator >> A (1, :)

equivalent to >> A (1,1: end)

Indexing of subregions >> A (1: 2 :) >> A ([1 2], :)

Indexing using logical expressions >> x(x > 0) % all elements of x where x>0. This is an array of booleans

Computational Intelligence, CI 2015

Introduction to MATLAB

13

Matrices functions Predefined elementary matrices >> I = eye (3) >> A = zeros (5,3)

>> A = ones (6,4)

Elementary functions are often overloaded and applicable to matrices >> help elmat >> sin (A)

Important matrix functions: >> repmat (A, 4, 1); >> reshape (A, 2, 2);

Computational Intelligence, CI 2015

Introduction to MATLAB

14

Numerical linear algebra Basic numerical linear algebra >> Z = [1, 2, 3]; x = inv (A) * Z

Many predefined standard functions >> det (A) >> rank (A)

>> eig (A)

The number of input / output arguments may vary >> [V, D] = eig (A)

Computational Intelligence, CI 2015

Introduction to MATLAB

15

Visualization in Matlab Visualization of vector data >> x = -pi: 0.1: pi; y = sin (x); >> figure; >> plot (x, y) >> hold on; >> plot (x, y, 'rs') >> xlabel ('x'); ylabel ('y = sin (x)');

Change of plot properties via "handle" >> h = plot (x, y); set (h, 'linewidth', 4);

Many other plot functions available (help Graph2D) >> v = 1: 4; pie (v) Computational Intelligence, CI 2015

Introduction to MATLAB

16

MATLAB Programming



Programming environment and path



M-file scripts and functions



Flow control



Programmer tips and tricks

Computational Intelligence, CI 2015

Introduction to MATLAB

17

Programming environment Working directory >> dir >> cd catalog >> pwd The path variable defines the MATLAB search path

>> Path >> addpath >> pathtool  Need access to functions in other directories MATLAB looks for a name in the following order: 1. variable in the current workspace 2. built-in variable 3. built-in m-file 4. m-file in the current directory 5. m-file in the search path

Computational Intelligence, CI 2015

Introduction to MATLAB

18

Script files Script files containing a sequence of MATLAB commands

Equivalent to the console input

factscript.m % FACT SCRIPT - Compute factorial n, n = 1 * 2 * ... * n! y = prod (1: n);

Executed (stored script in factscript.m) by >> n = 10; fact script; y

Works with variables in the global workspace  Variable n must exist before calling in the workspace  Variable y is created (or overwritten)  Comment lines begin with “%” Computational Intelligence, CI 2015

Introduction to MATLAB

19

Functions 

Functions are subroutines Have local variables (not global workspace) Parameter passing and return values Global variables only with extra keyword (globally) Used function [output_arguments] = function_name (input_arguments)

% comment lines

factfun.m function [z] = factfun (s) % FACTFUN - Compute factorial % Z = FACTFUN(N) z = prod (1: n);

>> y = factfun (10); Computational Intelligence, CI 2015

Introduction to MATLAB

20

Displaying code and Help List of code with the grade Command >> type factscript

The help Command displays the first comment lines >> help factscript

Computational Intelligence, CI 2015

Introduction to MATLAB

21

Logical expressions Relational operators (compare matrices gl. Size)

== (Equal to) < (Less than) > (Greater than)

~ = (Not equal) = (Greater than or equal to)

Logical Operators

& (And) | (Or) ~ (Not) Logical functions: xor isempty any all

if (x> = 0) & (x 170 disp ('tall') elseif height = 0, s(ii) = sqrt (x(ii)); else s(ii) = 0; end; end; toc Elapsed time is 0.053471 seconds.   

fast.m tic x = -250: 0.01: 250; s = zeros(size(x)); index = x> 0; s(index) = sqrt(x(index)); toc; Elapsed time is 0.030688 seconds.

Loops are slow: Use vector operations. Dynamic memory allocation requires a lot of time: memory Default Create empty matrices before the loop, not expand iteratively !! Computational Intelligence, CI 2015

Introduction to MATLAB

27

Advanced MATLAB Programming Functions  Variable number of inputs and outputs (See: nargin, nargout, varargin, varargout)  Local auxiliary functions

Other types of data:  Strings s = 'string';  Structures a.name = 'Alex';  Cell arrays A {1,1} = s; A {1,2} = a; Can store any type of data File handling:  Supports most C commands for file I / O (fprintf, ...) fprintf without fileHandle use for standard output. Computational Intelligence, CI 2015

Introduction to MATLAB

28

Advanced MATLAB Programming Object-oriented  Object "structure" + methods  Generation, transmission shown in the directory tree Graphical user interface  Based on the "handle" approach to graphics  Menus, buttons, slides and interactive graphics Interface to other code  Call of compiled C / C ++ ("mex"), Java and ActiveX

Computational Intelligence, CI 2015

Introduction to MATLAB

29

Data Visualization 1-Dimensional Data 

Histogram

>> hist (Accelerations, 20);



Box and Whisker Plot >> boxplot (Horsepower, org);

 

Box: Displays median and 1 and 3. quantile Whiskers: Displays outliers

Computational Intelligence, CI 2015

Introduction to MATLAB

30

Data Visualization 

2-D data: Scatter plots

>> gscatter (Weight, Horsepower, org, '', 'XOS')

Computational Intelligence, CI 2015

Introduction to MATLAB

31

Data Visualization More Dimensional Data gplotmatrix  

Scatterplot for 2 combinations of features Shows no multidimensional relationships

Computational Intelligence, CI 2015

Introduction to MATLAB

32

matlab.tugraz.at ssh -Y [email protected]

Computational Intelligence, CI 2015