what is matlab? - spsc · programming environment working directory >> dir >> cd...

31
1 Introduction to MATLAB Computational Intelligence, CI 2015 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

Upload: others

Post on 31-May-2020

21 views

Category:

Documents


0 download

TRANSCRIPT

1Introduction to MATLAB

Computational Intelligence, CI 2015

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

2Introduction to MATLAB

Computational Intelligence, CI 2015

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

3Introduction to MATLAB

Computational Intelligence, CI 2015

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

4Introduction to MATLAB

Computational Intelligence, CI 2015

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! :(

m-filesC-kernel

Sig. Proc. Neural

Networks

Contr. Syst.

5Introduction to MATLAB

Computational Intelligence, CI 2015

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/

6Introduction to MATLAB

Computational Intelligence, CI 2015

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)

7Introduction to MATLAB

Computational Intelligence, CI 2015

Variables and memory management

MATLAB uses double precision

>> format long

>> pi

ans = 3.141592653589793

>> format short

>> pi

ans = 3.1416

8Introduction to MATLAB

Computational Intelligence, CI 2015

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

9Introduction to MATLAB

Computational Intelligence, CI 2015

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

10Introduction to MATLAB

Computational Intelligence, CI 2015

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

11Introduction to MATLAB

Computational Intelligence, CI 2015

Indexing matrices

Indexing is by brackets

>> A (2,3)

1. Index: line

2. Index: Column

... Or partial matrices byRow 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)

12Introduction to MATLAB

Computational Intelligence, CI 2015

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

13Introduction to MATLAB

Computational Intelligence, CI 2015

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

14Introduction to MATLAB

Computational Intelligence, CI 2015

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)

15Introduction to MATLAB

Computational Intelligence, CI 2015

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)

16Introduction to MATLAB

Computational Intelligence, CI 2015

MATLAB Programming

Programming environment and path

M-file scripts and functions

Flow control

Programmer tips and tricks

17Introduction to MATLAB

Computational Intelligence, CI 2015

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

18Introduction to MATLAB

Computational Intelligence, CI 2015

Script files

Script files containing a sequence of MATLAB commands

Equivalent to the console input

% FACT SCRIPT - Compute factorial n, n = 1 * 2 * ... * n!

y = prod (1: n);

factscript.m

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 “%”

19Introduction to MATLAB

Computational Intelligence, CI 2015

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

<function body>

function [z] = factfun (s)

% FACTFUN - Compute factorial

% Z = FACTFUN(N)

z = prod (1: n);

factfun.m

>> y = factfun (10);

20Introduction to MATLAB

Computational Intelligence, CI 2015

Displaying code and Help

List of code with the grade Command

>> type factscript

The help Command displays the first comment lines

>> help factscript

21Introduction to MATLAB

Computational Intelligence, CI 2015

Logical expressions

Relational operators (compare matrices gl. Size)

== (Equal to) ~ = (Not equal)< (Less than) <= (Less than or equal to)> (Greater than) > = (Greater than or equal to)

Logical Operators

& (And)| (Or)~ (Not)

Logical functions:xorisemptyanyall

if (x> = 0) & (x <= 10)

disp ('x is in range [0,10]')

else

disp ('x is out of range')

end

22Introduction to MATLAB

Computational Intelligence, CI 2015

Flow control - Selection

The if-elseif-else construction

if <logical expression>

<Commands>

elseif <logical expression>

<Commands>

else

<Commands>

end

if height> 170

disp ('tall')

elseif height <150

disp ('small')

else

disp ('average')

end

23Introduction to MATLAB

Computational Intelligence, CI 2015

Flow control - Repetitions

Fixed number of repetitions

for index = <vector>

<statements>

end

In each iteration, the variable is index the next value of <vector>

assigned.

for k = 1: 12

kfac = prod (1: k);

fprintf ('%d: factorial %d \ n', k, kfac)

end

24Introduction to MATLAB

Computational Intelligence, CI 2015

Flow control - conditional repetition

while-loops

<statements> is processed, unless <logical expression> is true.

while <logical expression>

<statements>

end

k = 1;

while prod (1: k) ~ = Inf,

k = k + 1;

end

fprintf ('Largest factorial in matlab: %d \ n', k-1);

25Introduction to MATLAB

Computational Intelligence, CI 2015

Programmer tips and tricks

tic;

x = -250: 0.01: 250;

for ii = 1: length (x)

if x(ii )>= 0,

s(ii) = sqrt (x(ii));

else

s(ii) = 0;

end;

end;

toc

Elapsed time is 0.053471 seconds.

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.

slow.m

fast.m

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

27Introduction to MATLAB

Computational Intelligence, CI 2015

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.

28Introduction to MATLAB

Computational Intelligence, CI 2015

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

29Introduction to MATLAB

Computational Intelligence, CI 2015

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

30Introduction to MATLAB

Computational Intelligence, CI 2015

Data Visualization

2-D data: Scatter plots

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

31Introduction to MATLAB

Computational Intelligence, CI 2015

Data Visualization

More Dimensional Data

gplotmatrix

Scatterplot for 2 combinations of features

Shows no multidimensional relationships

32Introduction to MATLAB

Computational Intelligence, CI 2015

matlab.tugraz.at

ssh -Y [email protected]