introduction to matlab michael fink [email protected]

29
Introduction to MATLAB Michael Fink [email protected] • Login and press the Matlab icon • Part 1: Using vectors and matrices • Part 2: Performing calculations • Part 3: Programming basics • Part 4: Visualization (graphs) • Part 5: Functions & function handles

Upload: griffith-quinn

Post on 30-Dec-2015

63 views

Category:

Documents


1 download

DESCRIPTION

Introduction to MATLAB Michael Fink [email protected]. Login and press the Matlab icon Part 1: Using vectors and matrices Part 2: Performing calculations Part 3: Programming basics Part 4: Visualization (graphs) Part 5: Functions & function handles. Introduction to matlab. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Introduction to MATLABMichael Fink [email protected]

• Login and press the Matlab icon

• Part 1: Using vectors and matrices• Part 2: Performing calculations• Part 3: Programming basics• Part 4: Visualization (graphs)• Part 5: Functions & function handles

Page 2: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Introduction to matlab

• A technical computing environment for high performance numeric computation and visualization

• No. 1 software development environment in the academia and in industry research

• Quick coding (not efficient in running time)

• A lot of existing code is available in the matlab core, toolboxes and internet

Page 3: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Getting started with Matlab

• Press on the Matlab icon (and wait…)

• Matlab is a functional languagethe Matlab prompt is >>

Write:

>> 100+1

ans =

101

Page 4: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Getting started with Matlab

Define variables (use meaningful names):

>> income = 3000

income =

3000

>> car = 1000;

>> rent = 2000;

>> x = income - car - rent

x =

0

Page 5: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Language elements: Data types• Matrices arrays of similar elements

>> a = rand(3) % a double matrix>> b = (a>0.9) % a logical matrix

• Strings >> myName = 'Michael Fink'>> myName(4:5) % returns 'ha'

• Cells arrays of different types of elements>> c{1,1} = 'Michael Fink'>> c{1,2} = 3000

• Structs variables with different fields>> me.myName = 'Michael Fink'>> me.income = 3000>> you = me

Notice: no pointers

Page 6: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Scripts, functions and the matlab path

• Three places to write code– Prompt: write and press enter– Script file: file name / F5 / mark code and F9

>> edit myscript.m

– Function file: file name and parameters • (details later)

• Notice: prompt and script variables share the same scope (unlike function variables)

Page 7: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Scripts, functions and the matlab path

• When using files be sure they're on the matlab path:

>> editpath % selecting the appropriate directory

Or

>> cd C:\work\

Or

Select path at the top of the Matlab prompt window

Page 8: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Help!

>> help sum

Page 9: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Vectors, matrices and indicesMatlab basic variable is matrices (vectors are 1-D matrices)

>> h0 = zeros(1,3)h0 =

0 0 0>> v0 = zeros(3,1)v0 =

0 0 0

>> vec1 = [3:8]vec1 =

3 4 5 6 7 8>> mySkip = [3:2:8]mySkip =

3 5 7

Page 10: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

When defining a vector:

, or space for insertion in same row

; for insertion in same column

Vectors, matrices and indices

>> row = [1 7 13 2]

>> col = [1;7;13;2]

Page 11: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Concatenating matrices>> hCat = [h0 mySkip]

hCat =

0 0 0 3 5 7

>> vCat = [h0; mySkip]

vCat =

0 0 0

3 5 7

>> skip3 = repmat(mySkip,3,1)

skip3 =

3 5 7

3 5 7

3 5 7

Page 12: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Running example:

Year = [2 0 0 6]

MonthDay = [0 0 0 0]

Basic = [MonthDay Year ]

November = repmat( Basic, 30, 1)

Page 13: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Concatenating matrices>> x = ones(2)x =

1 11 1

>> y = eye(2)y =

1 00 1

>> x(1,:) = [3 5]x =

3 51 1

>> y(:,2) = [3;5]y =

1 30 5

Page 14: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Indices

>> Rand3(2:3,2) = 0Rand3 =

0.9501 0.4860 0.45650.2311 0 0.01850.6068 0 0.8214

>> Rand3(5:6) = 0

Rand3 =

0.9501 0.4860 0.4565

0.2311 0 0.0185

0.6068 0 0.8214

>> Rand3=rand(3)

Rand3 =

0.9501 0.4860 0.4565

0.2311 0.8913 0.0185

0.6068 0.7621 0.8214

Page 15: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Running example:

Year = [2 0 0 6]

MonthDay = [0 0 0 0]

Basic = [MonthDay Year ]

November = repmat(Basic,30,1)

November(:,3:4) = ones(30,2)

November(10:19,1) = 1

November(20:29,1) = 2

November(30,1) = 3

November(1:9, 2) = [1:9]'

November(:,2) = repmat(November(1:10, 2),3,1)

Page 16: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Common operations• Mathematical operations: + - * / ^

>> 3+(4/6)*8-12^0>> a = rand(3) - 0.5>> eye(3)*a

• Logical operations: ~1 is 0>> a<=0 % or a<=zeros(3)

will return 3x3 logical matrices~= <= >= == & |

isequal (not ==) tests whether matrices are identical

Page 17: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Common operations• Element functions:

– mod (e.g. mod([3:5],4) is [3, 0, 1])– ceil, round, sqrt, sign, .*, .^ , ' (transpose)

>> sqrt([4 9])>> ones(3,1).*zeros(1,3)'

• Column-wise functions: sum, max, mean>> sum(a) % similar to ones(1,3)*a

• traits of the variables: length, size >> size(a)

Page 18: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Running example:students = ['yitzhak ';'Shimon ';'Benjamin ']

Leadership = [94; 90; 77]

Economics = [78; 84; 94]

(Leadership + Economics) / 2

Leadership > 85

bonus = [1.05 1.05 1.00]

floor(Leadership.*bonus) % generates an error

floor(Leadership.*bonus')

mean(Leadership)

sum(Leadership/3)

var(Economics)

Page 19: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Some vector operations• find

>> find(x==max(x))• sort

>> [Y I] = sort(x)

Running example:students(find(Economics==max(Economics)),:)

[vector index] = sort(Economics,'descend')

students(index,:)

setdiff(Economics,Leadership)

Page 20: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Saving and loading variables in current matlab path

>> save myVars x>> x = randn(5,3);>> load myVars

Page 21: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Language elements: if conditions

inChar='67/0';

i=3;

val1 = str2num(inChar(1:i-1));

val2 = str2num(inChar(i+1:end));

if val2==0

okInput = false

else

exVal= val1 / val2

end

Page 22: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Language elements: switch conditionsinChar = '65*20';i = 3;val1 = str2num(inChar(1:i-1));val2 = str2num(inChar(i+1:end));switch inChar(i)

case '*', exVal= val1 * val2

case '/', if val2==0

okInput=0; else exVal= val1 / val2

end otherwise i=i+1;end

Page 23: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Language elements: Loops• for loops

for i=1:10,for j=1:10,

m(i,j)=i*j;end

endm

% for loops are often unnecessary in Matlab m=[1:10]'*[1:10]• while loops

total = 0;while total<1000

itemPrice = input(' enter product price: ');if itemPrice==0, break; endtotal = total + itemPrice;

endtotal

Page 24: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

inChar = input('enter formula: ','s');okInput = true;i=1;while okInput == true switch inChar(i)

case '*', finalVal=str2num(inChar(1:i-1))*str2num(inChar(i+1:end)); break case '/', if str2num(inChar(i+1:end))==0 okInput = false; else finalVal=str2num(inChar(1:i-1))/str2num(inChar(i+1:end)); break end otherwise i=i+1; endendif okInput, disp(['is ' num2str(finalVal)]);else 'div by 0!'end

Copy paste into myscript.m and

press F5

Page 25: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Visualization: plots

figure(1);x = -5:0.1:5; y = cos(x); plot(x,y)hold on;y2 = sin(x); plot(x, y, 'm', x, y2, 'g.');axis([-2*pi 2*pi -1 1]);axis tight;

Page 26: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Visualization: images% display noisy matrix

clf;

imagesc(randn(10));

title('noisy x');

axis square;

Page 27: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Language elements: functions• Functions are called externally with some input,

use their own variables and return an output

• Several functions could be defined in a single file but only the heading function (with the same name as the file) will be available externally

>> edit myfunc.mfunction [x2, x3, x4] = myfunc(x)x2 = x.^2;x3 = x.^3;x4 = x.^4;

Copy paste into myfunc.m

Page 28: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Function handlesfunctions as variables: efficient when different functions need to be used in the same way

a=0; b=pi/2; dt=0.001;for i=1:3 switch i case 1, f1=@sin; case 2, f1=@sqrt; case 3, f1=@myfunc; end ff = f1([a:dt:b]); ['integral = ' num2str(sum(ff*dt))]end

Page 29: Introduction to MATLAB Michael Fink  fink@cs.huji.ac.il

Matlab is endless

• Linear algebra– det (matrix determinant)– eig (eigenvalues and get eigenvectors)

• Optimization toolbox– Linear / quadratic programming

• Statistics toolbox• Neural Network Toolbox• Symbolic toolbox• Image processing toolbox• …