introduction and matlab basics - tu berlin · matlab is optimised for the manipulation of matrices...
TRANSCRIPT
Introduction andMATLAB Basics
ComputerRoom
Lecture
MATLAB
Further information in the tutorial: http://www.cv.tu-berlin.de/lehre/cv/dbv/matlab.pdf
!Use the MATLAB Help System!
● MATLAB: Matrix Laboratory, designed for matrix manipulation● Pro:
➔ Syntax similar to C/C++/Java➔ Automated memory management➔ Dynamic data types➔ Single instructions manipulate entire vectors and matrices➔ A wide range of libraries for signal processing, visualisation, machine learning...➔ Platform independent, inclusion of C/C++/Java/... modules possible
● Con:➔ Costs money➔ Uses lots of memory➔ Can be slow for certain types of problems
VariablesScalars
>> a = 5
a =
5>>
>> a = 5;>> a
a =
5>>
(Semicolon suppresses output)
Matrices
>> a = [1,2,3]
a =
1 2 3>>
Elements of a row are separated by commas >> a = [1,2,3;
4,5,6]
a =
1 2 3 4 5 6>>
Rows are separated by semicolons
Basic Datatypes● double: Floating point number, the most common datatype in MATLAB
➔ Other numeric datatypes: float, int32, uint8, ... rather uncommon
● Complex numbers
● Strings
>> a = complex(1,-2)a = 1.0000 - 2.0000i
>> a = 1-2*ia = 1.0000 - 2.0000i
Warning: i can be redefined
(overwritten)!
>> a = 1; whos('a'); Name Size Bytes Class a 1x1 8 double arrayGrand total is 1 element using 8 bytes
>> a = ['test123', '456']a =test123456
Advanced Datatypes
>> a = {[1,2,3], 'test123'}a = [1x3 double] 'test123'
>> a.b = 2; a.c = [2,3,4];>> aa = b: 2 c: [2 3 4]
● Cell Arrays: Generalised matrix➔ Elements can have differing datatypes➔ Elements can have different sizes
● Structures➔ Combine various data in a 'field/value' type structure➔ Fields and associated datatypes do not have to be declared (and can
change at run-time)
Arithmetic Operators 1
● Addition and subtraction
>> a = 5; b=6;>> a + b
ans =
11>>
>> a = [1,2,3; 4,5,6]; b = [0,1,2; 3,4,5];>> a - b
ans =
1 1 1 1 1 1>>
>> a = [1,2; 3,4]; b = [1;2;3];>> a + b??? Error using ==> plusMatrix dimensions must agree.
>> a = [1,2; 3,4];>> a + 5
ans =
6 7 8 9>>
● Matrices must have the same size to be added or subtracted➔ Exception: Scalars can be added to matrices
Arithmetic Operators 2
● The * operator is used for matrix multiplication
>> a = 5; b = 6;>> a * b
ans =
30>>
>> a = [0,1; 1,0]; b = [1;2];>> a * b
ans =
2 1>>
>> a = [1,2; 3,4];>> a * 2
ans =
2 4 6 8>>
>> a = [1; 2]; b = [2; 1];>> a .* b
ans =
2 2>>
● The .* operator multiplies corresponding elements of the operands
Arithmetic Operators 3
>> a = 2; b = 3;>> a / b
ans =
0.6667>>
>> a = 2; b = [1,2; 3,4];>> a ./ b
ans =
2.0000 1.0000 0.6667 0.5000>>
>> a = [1,2; 3,4]; b = [2,1; 1,2];>> a ./ b
ans =
0.5000 2.0000 3.0000 2.0000>>
● Division with / has the expected effect for scalars
● In the case of matrices, the ./ operator causes element-wise division
● Matrices can also be divided using the / operator. This operation solves the system of linear equations associated with the matrices involved
Arithmetic Operators 4
● Scalars and matrices can be raised to a power using ^ and .^ respectively
● For matrices, the ^ operator is equivalent to repeated matrix multiplication
>> a = 5;>> a ^ 2
ans =
25>>
>> a = [1,2; 3,4];>> a .^ 2
ans =
1 4 9 16>>
>> a = [1,2; 3,4];>> a ^ 3ans =
37 54 81 118>>
>> a = [1,2; 3,4];>> a * a * aans =
37 54 81 118>>
Logical Operators● In MATLAB, True and False are represented by 1 and 0, repectively● The operators {==, ~=} test the operands for equality
● The operators{>, <, >=, <=} compare the magnitudes of operands
● All logical operators can be applied to matrices, where they act on each element
>> a = 5; a < 3ans =
0>>
>> a = 5; a >= 5ans =
1>>
>> a = [1,2; 3,4];>> a == 3ans =
0 0 1 0>>
>> a = [1,2; 3,4]; b = [1,0; 3,0];>> a > bans =
0 1 0 1>>
>> a = 3; a == 0ans =
0>>
>> a = 3; a ~= 0ans =
1>>
Working with Matrices 1● Matrices do not have to be created by explicitly listing their contents
● ones(rows, columns) initialises a matrix of ones
● zeros(rows, columns) initialises a matrix of zeros
● zeros and ones can also be used to create higher dimensional (3D,4D etc.) matrices
● a:b initialises a vector [a, a+1, a+2, ... , b]
● a:c:b initialises a vector [a, a+c, a+2*c, ... , b]
>> ones(2,3)
ans =
1 1 1 1 1 1>>
>> 1:5
ans =
1 2 3 4 5>>
>> 2:-0.5:1
ans =
2.0000 1.5000 1.0000>>
>> zeros(2,3)
ans =
0 0 0 0 0 0>>
Working with Matrices 2● MATLAB indices start at 1
● a(y,x) is the value of a in row y and column x
● Several matrix locations can be accessed simultaneously using lists of indices● The special index “:” accesses an entire dimension of a matrix
● Elements in a matrix can be addressed using only a single index (see “Linear Indexing” in
the MATLAB Help system)
>> a = [1,2; 3,4];>> a(2,1)
ans =
3>>
>> a = [1,2; 3,4];>> a([1,2],2)
ans =
2 4>>
>> a = [1,2; 3,4];>> a(1:2,2)
ans =
2 4>>
>> a = [1,2; 3,4];>> a(:,2)
ans =
2 4>>
Working with Matrices 3● The ' operator transposes a matrix and (complex) conjugates each element
● The size function determines the size of a matrix
● Other important functions include:● min, max: Find the minimal/maximal value in a vector● sum: Sum the elements of a vector● mean, std: Mean and standard deviation in a vector● find: Find the indices of elements that satisfy a certain condition● abs: Compute the absolute value
>> a = [1,2; 3,4];>> a'
ans =
1 3 2 4>>
>> a = [1,2; 3,4];>> a
a =
1 2 3 4>>
>> a = ones(10,100); size(a)
ans =
10 100>>
Flow Control 1
if Syntax
if logical-valueInstruction 1Instruction 2...
elseInstruction 3Instruction 4...
end
If Example
>> a = 1;>> if (a >= 0)
disp('a ist > 0!'); enda ist > 0!>>
● Conditional statements use if
● The else part of an if statement is optional
● A sequence of if statements can often be replaced by a single switch statement (see
MATLAB Help!)
Flow Control 2
for Syntax
for Variable = ListInstruction 1Instruction 2...
end
for Example 1
>> for i=[2,4,6]disp(i);
end
2 4 6>>
for Example 2
>> for i=1:3disp(2*i);
end
2 4 6>>
for Loops
while Loops
whlie Syntax
while ConditionInstruction 1Instruction 2...
end
while Example
>> a = 6;>> while (a > 0)
disp(a);a = a-4;
end
6 2>>
Writing Functions 1
Important● MATLAB will only find your .m file if the directory containing it is
either● set as the “Current Directory” in the main window● or is permanently added to the search path using File ->
Set Path...
● New (user defined) functions are defined in .m files
● The file name has to correspond to the function name
➔ E.g. the function myFunc is defined in myFunc.m
● New .m Files can be created using the menu item File -> New -> M-File
● Several functions can be defined in a single .m file, however only the main program is visible to the outside
Writing Functions 2
● A function begins with a declaration that contains the function name and lists inputs (parameters) and outputs:
● output1, output2 ...: The outputs, or results, of the function● input1, input2 ...: The input parameters to the function● Name: The name of the function
● A very simple MATLAB function could be the following:
● Comments in MATLAB Programms begin with %, as shown above
function [output1, output2, output3, ... ]=Name(input1, input2, ... )
% Function test1:% Computes the sum of in1 and in2
function [out]=test1(in1, in2)out = in1 + in2;
end
Writing Functions 3
>> summe = test2(5,6); >> [summe, diff] = test2(5,6);
>> total = test1(5,6);>> totalans =
11>>
% Function test2:% Computes the sum and the difference of in1 und in2
function [out1, out2]=test2(in1, in2)out1 = in1 + in2;out2 = in1 - in2;
end
● Functions can be executed in the MATLAB main window
● Several outputs are possible by simply assigning values to all output variables:
● Not all outputs of a function have to be used (assigned) by the caller
Graphics
● The figure command opens a new window for graphical output
● The close command closes the currently active figure
>> figure>>
plot
>> plot([-5:5].^2)>> title('Parabola')>> xlabel('X')>> ylabel('Y')>> legend('x^2')
>> x = cos(0:0.1:2*pi)>> y = sin(0:0.1:2*pi)>> plot(x,y)
imshow
>> imshow(diag(0:200),[ ])>> colorbar>>
● imshow displays matrices as images
● The empty square braces indicate that intensities are automatically scaled (minimum and maximum become black and white, respectively)
● The example above displays a matrix with the values [0:200] on the diagonal
● imshow can also display colour images
imread & subplot
>> rgb = imread('img/desert.jpg');>> grau = rgb2gray(rgb);>> subplot(2,1,1)>> imshow(rgb)>> subplot(2,1,2)>> imshow(grau)>>
●imread reads an image from a file
●In the case of colour images, the result is a 3D matrix with RGB values
●rgb2gray converts colour images to grayscale
●subplot is used to display several graphics outputs in a single window
>> rgb = imread('img/desert.jpg');>> grau = double(rgb2gray(rgb));
For image processing and analysis, it is almost always necessary to cast grayscale values to the 'double'
datatype:
Breakpoints
>> test1([1,2], ones(2))??? Error using ==> plusMatrix dimensions must agree.
Error in ==> test1 at 5out = in1 + in2;
>> test1([1,2], ones(2))5 out = in1 + in2;K>> in1, in2in1 = 1 2
in2 = 1 1 1 1
● The execution of a function can be halted at arbitrary points using breakpoints➔ The contents of variables at the breakpoint in the function can be viewed and changed➔ This is often usefull when debugging functions
Breakpoints are enabled by clicking onthe '-' marker at the beginning of a line
Automatically Switching to Debug Mode
(The Debug menu in the main window)
(Enable the debug mode automatically incase of an error)
● MATLAB can be configured to switch to debug mode automatically, as soon as an error occurs➔ Usefull when there are several potential sources of errors
Exercises
● MATLAB is optimised for the manipulation of matrices
● Loops in which elements of a matrix are processed individually are very slow
● Good MATLAB programs therefore avoid loops all together
● Surprisingly many problems can be solved by manipulating entire matrices without explicit iteration, even when the solution is sometimes more memory intensive
● The aim of this exercise is, therefore, to solve a number of simple and not so simple tasks without using explicit loops over matrices (i.e. no for or while loops allowed!)
● The following slides describe the prototypes of the functions to be implemented
function splitShow(imgA,imgB)
>> imgA = imread('img/desert.jpg');>> imgA = double(rgb2gray(imgA));>> imgB = edge(imgA,'canny');>> splitShow(imgA,imgB)>>
● A processed image (imgB) is to be compared with the original (imgA)
● Both images are cut in half and concatenated to make their comparison easy● Both intensities in both images need to be scaled such that their gray values lie in the same range
before the two image halves are concatenated
function [n]=matchCount(A,num)
● Function matchCount counts how often a given number num occurs in matrix A
>> A = [1,2; 2,3]
A =
1 2 2 3>> matchCount(A,1)
ans =
1>>
>> A = [1,2; 2,3]
A =
1 2 2 3>> matchCount(A,2)
ans =
2>>
function [A]=replicate(vect, num)
● The vector vect is repeated num times to produce matrix A
● vect can be a row-vector or a column-vector
● Do not use the MATLAB repmat function!
>> a = [1,2,3,4]
a =
1 2 3 4>> replicate(a,5)
ans =
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4>>
>> a = [1;2;3;4]
a =
1 2 3 4>> replicate(a,5)
ans =
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4>>
function [circ]=circle(radius)
>> imshow(circle(100),[])>>
>> circle(4)
ans =
0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 0 0 0 0 0 0 1 0 0 0 0
>>
1.4142 1.0000 1.41421.0000 0 1.00001.4142 1.0000 1.4142
ExampleDistances for radius = 1
● circle computes a quadratic matrix circ with (2*radius+1) rows and columns
● circ contains a region of 1s in the shape of a circle (of radius radius)
● Hint: Begin by computing a matrix of distances to the centre element of the matrix
➔ The replicate function could come in handy