introduction to matlab michael fink fink@cs.huji.ac.il
Post on 30-Dec-2015
53 Views
Preview:
DESCRIPTION
TRANSCRIPT
Introduction to MATLABMichael Fink fink@cs.huji.ac.il
• 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
• 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
Getting started with Matlab
• Press on the Matlab icon (and wait…)
• Matlab is a functional languagethe Matlab prompt is >>
Write:
>> 100+1
ans =
101
Getting started with Matlab
Define variables (use meaningful names):
>> income = 3000
income =
3000
>> car = 1000;
>> rent = 2000;
>> x = income - car - rent
x =
0
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
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)
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
Help!
>> help sum
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
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]
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
Running example:
Year = [2 0 0 6]
MonthDay = [0 0 0 0]
Basic = [MonthDay Year ]
November = repmat( Basic, 30, 1)
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
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
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)
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
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)
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)
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)
Saving and loading variables in current matlab path
>> save myVars x>> x = randn(5,3);>> load myVars
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
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
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
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
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;
Visualization: images% display noisy matrix
clf;
imagesc(randn(10));
title('noisy x');
axis square;
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
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
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• …
top related