Multimedia Security: Introduction to Matlab Riccardo Lazzeretti lazzeretti@diism.unisi.it Lab LTT (240, second floor) Outline • • • • • • • • • What is Matlab? Matlab layout Variables, array, matrix, string, indexing Operators (Arithmetic, relational, logical ) Display Facilities Flow Control Using of M-File Writing User Defined Functions Workspace What is Matlab? • Matlab (MATrix LABoratory) is basically a high level language which has many specialized toolboxes for making data analysis easy • Interactive environment ▫ Commands interpreted one line at a time ▫ Own functions or procedures may be scripted • Enriched by thematic toolbox ▫ ▫ ▫ ▫ Image acquisition Financial Signal processing … • Too broad for our purposes in this course Matlab Layout • Command Window ▫ type commands • Current Directory ▫ View folders and m-files • Workspace ▫ View program variables ▫ Double click on a variable to see it in the Array Editor • Command History ▫ view past commands ▫ save a whole session using diary • Configurable Intarface ▫ Other windows… Help!!! Variables • No need for type declaration: int a; double b; float c; • Matlab works with double precision (unless specified) matrices • Variables are 1x1 matrices Example: >>x=5; >>x1=2; • Particular values predefined: ▫ ▫ ▫ ▫ ▫ pi : π eps: Euler’s number i or j: imaginary unit inf: infinite (division by 0 is allowed) NaN: Not a Number (inf - inf) • Matlab is case sensitive ▫ A is different from a Array, Matrix • a vector In the help: Matlab Mathematics Matrices and arrays x = [1 2 5 1] x = 1 2 5 • a matrix 1 M = [1 2 3; 5 1 4; 3 2 -1] M = 1 5 3 2 1 2 3 4 -1 • Column vector and transpose y = x’ w = [3 5 7]’ z = [1; 9; 2] y = w = 1 2 5 1 z = 3 5 7 1 9 2 Series • t =1:10 t = 1 2 k =2:-0.5:-1 • 3 4 1 0.5 5 6 7 8 k = 2 • B 1.5 = [1:4; 5:8] x = 1 5 2 6 3 7 4 8 0 -0.5 -1 9 10 Matrices automatically generated • zeros(M,N), MxN matrix of zeros • zeros(M) stands for zeros(M,M) • ones(M,N) MxN matrix of ones • ones(M) stands for ones(M,M) • eye(M)generates the identity matrix • rand(M,N) MxN matrix of uniformly distributed random numbers on [0,1) ▫ randn(M,N) for normal distribution • magic(M) ??? x = zeros(1,3) x = 0 0 x = ones(1,3) x = 1 1 0 1 x = eye(2) x = 1 0 0 1 x = rand(1,3) x = 0.9501 0.2311 0.6068 Other data types • Boolean In the help: Matlab Programming Fundamentals Classes (Data Types) ▫ logical • Integers ▫ int8, int16, int32, int64 ▫ uint8, uint16, uint32, uint64 • Text ▫ char • Containers ▫ cell ▫ struct Matrix Index • The matrix indices begin from 1 (not 0 (as in C)) • The matrix indices must be positive integer Given: A(-2), A(0) Error: ??? Subscript indices must either be real positive integers or logicals. A(4,2) Error: ??? Index exceeds matrix dimensions. Matrix index (2) • end indicates the last element • End • «:» indicates all the elements and can be used to select a row, a column or a sub-matrix Variable display 1. Writing the variable name ▫ «;» prevents displaying the variable 2. By using the command disp 3. From the workspace ▫ ▫ It provides a variable preview Variable editor can be opened by double-clicking on the variable name Concatenation of Matrices • x = [1 2], y = [4 5], z=[ 0 0] A = [ x y] 1 2 4 5 B = [x ; y] 1 2 4 5 C = [x y ;z] Error: ??? Error using ==> vertcat CAT arguments dimensions are not consistent. Operators (arithmetic) • Arithmetic operators In the help: + addition Matlab - subtraction Programming Fundamentals * multiplication Basic Program Components Operators / division ^ power complex conjugate transpose • Logical operators ~ not | or & and • Relational operators <, <= lower than >, >= greater than == equal to ~= Not equal to Matrices Operations Given A and B: Addition Subtraction Product Transpose Operators (Element by Element) .* ./ .^ element-by-element multiplication element-by-element division element-by-element power Defined x=A(1,:) and y=A(2,:) K= x^2 Error: ??? Error using ==> mpower Matrix must be square. B=x*y Error: ??? Error using ==> mtimes Inner matrix dimensions must agree. Fuctions • A function is used as usual ▫ <output>=function(<inputs>) ▫ A function in Matlab can return more output matrices A=function(X) stores the first output in A [A,B]=function(X) stores the first output in A and the second in B • The most important functions: ▫ help <name> provides a function descritpion in the command window ▫ doc <name> opens the help Some Built-in functions • • • • • • • • • • mean(A):mean value of a vector max(A), min (A): maximum and minimum sum(A): summation. sort(A): sorted vector median(A): median value std(A): standard deviation. det(A) : determinant of a square matrix dot(a,b): dot product of two vectors Cross(a,b): cross product of two vectors Inv(A): Inverse of a matrix A • ATTENTION: If applied to a matrix, many of them operate on columns Dimensional functions • Given A=rand(3,4), B=[], x=[1,2,3] • isempty() returns logical 1 (true) if the matrix is an empty array and logical 0 (false) otherwise. • size() returns the number of row and columns of a matrix ▫ Can be used to obtain only the number of rows [size(…,1)] or columns [size(…,2)] • length() returns the number of elements in an array or the number of columns in a matrix ▫ If applied to a matrix returns the biggest among the number of rows and columns Function Plot sin(x) between 0≤x≤4π • Create an x-array of 100 samples between 0 and 4π. Equivalent to >>x=linspace(0,4*pi,100); x=0:4*pi/100:100 • Calculate sin(.) of the x-array 1 >>y=sin(x); 0.8 0.6 0.4 0.2 • Plot the y-array >>plot(y) 0 -0.2 -0.4 -0.6 -0.8 -1 0 10 20 30 40 50 60 70 80 90 • doc plot to see plot parameters and configuration 100 Alternative way to plot variables 3. Matlab plots the variable 2. Click plot button 1. Select the variable Exercise: Plot e-x/3sin(x) between 0≤x≤4π • Create an x-array of 100 samples between 0 and 4π. >>x=linspace(0,4*pi,100); • Calculate sin(.) of the x-array >>y=sin(x); • Calculate e-x/3 of the x-array >>y1=exp(-x/3); • Multiply the arrays y and y1 >>y2=y*y1; Exercise: Plot e-x/3sin(x) between 0≤x≤4π • Multiply the arrays y and y1 correctly >>y2=y.*y1; • Plot the y2-array 0.7 0.6 >>plot(y2) 0.5 0.4 0.3 0.2 0.1 0 -0.1 -0.2 -0.3 0 10 20 30 40 50 60 70 80 90 100 Display Facilities • title(.) >>title(‘This is the sinus function’) • xlabel(.) This is the sinus function 1 0.8 >>xlabel(‘x (secs)’) 0.6 0.4 sin(x) • ylabel(.) 0.2 0 -0.2 >>ylabel(‘sin(x)’) -0.4 -0.6 -0.8 -1 0 10 20 30 40 50 60 x (secs) 70 80 90 100 Display Facilities 0.7 0.6 • plot(.) 0.5 0.4 0.3 0.2 >>x=linspace(0,4*pi,100); >>y=sin(x).*exp(-x/3); >>plot(y) >>plot(x,y) • stem(.) 0.1 0 -0.1 -0.2 -0.3 0 10 20 30 40 50 60 70 80 90 100 0 10 20 30 40 50 60 70 80 90 100 0.7 0.6 0.5 0.4 >>stem(y) >>stem(x,y) 0.3 0.2 0.1 0 -0.1 • Others… -0.2 -0.3 Graphics - Overlay Plots Use hold on for overlaying graphs So the following: Gives: >> >> >> >> >> >> x=linspace(0,4*pi,100); y=sin(x); z=sin(x).*exp(-x/3); plot(x,y, ‘b’); hold on; plot(x, z, ’r’); Histogram • hist() shows the distribution of data values • Defined A= floor(rand(20)*50) hist(A) hist(A(:)) hist(A(:),50) Flow Control • • • • • if for while break …. Control Structures • If Statement Syntax if (Condition_1) Matlab Commands elseif (Condition_2) Matlab Commands elseif (Condition_3) Matlab Commands else Matlab Commands end Some Dummy Examples if ((a>3) && (b==5)) Some Matlab Commands; end if (a<3) Some Matlab Commands; elseif (b~=5) Some Matlab Commands; end if (a<3) Some Matlab Commands; else Some Matlab Commands; end Control Structures • For loop syntax for i=Index_Array Matlab Commands end Some Dummy Examples for i=1:100 Some Matlab Commands; end for j=1:3:200 Some Matlab Commands; end for m=13:-0.2:-21 Some Matlab Commands; end for k=[0.1 0.3 -13 12 7 -9.3] Some Matlab Commands; end Control Structures • While Loop Syntax while (condition) Matlab Commands end Dummy Example while ((a>3) && (b==5)) Some Matlab Commands; end Editor Click to create a new M-File Click to open an existing M-File • Extension “.m” • A text file containing script or function or program to run Use of M-File File saved as Denem430.m If you include “;” at the end of each statement, result will not be shown immediately User Defined Functions • Functions are m-files which can be executed by specifying some inputs and supply some desired outputs. • The code telling the Matlab that an m-file is actually a function is function out1=functionname(in1) function out1=functionname(in1,in2,in3) function [out1,out2]=functionname(in1,in2) • You should write this command at the beginning of the m-file and you should save the m-file with a file name same as the function name • A .m file must contain a single function • Example ▫ Write a function : out=squarer (A, ind) Which takes the square of the input matrix if the input indicator is equal to 1 Or takes the element by element square of the input matrix if the input indicator is equal to 2 Same Name Writing User Defined Functions • Other example: ▫ A function which takes an input array and returns the sum and product of its elements as outputs ▫ The function sumprod(.) can be called from command window Notes: • “%” is the neglect sign for Matlab (equaivalent of “//” in C). Anything after it on the same line is neglected by Matlab compiler. • Sometimes slowing down the execution is done deliberately for observation purposes. You can use the command “pause” for this purpose pause %wait until any key pause(3) %wait 3 seconds Files in Matlab • • • • • c-like functions to manage file exist fopen(), fclose() open and close files fread(), fscanf() read from the file fwrite(), fprintf() write in the file … • There is a easier way!!! In the help: Matlab Function reference File I/O Workspace Open the variable editor Import data (workspace, text, images…) • Commands: ▫ load ▫ save • Unfortunately it cannot be done automatically Save the workspace in a .mat file Loading text file • The file is placed in a cell having the name of the file (without extension) • Conversion to string (array of characters): ▫ str=char(<filename>); • The i-th character can be addressed as usual ▫ str(i) Debugging Temporary variables can be evaluated in the workspace Flow controls Breakpoint The command window can be used to evaluate other functionalities, display values or plot variables as usual Suggestion • Matlab is an interpreted language • Standard functions are more efficient than user defined functions Avoid cicles, if possible