Matlab tutorial Da-Chuan Cheng 20.10.2006 Münster (Westf.) Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment. It is a mainstay of the Mathematics Department software lineup and is also available for PC's and Macintoshes and may be found on the CIRCA VAXes. Matlab is well adapted to numerical experiments since the underlying algorithms for Matlab's builtin functions and supplied m-files are based on the standard libraries LINPACK and EISPACK. Matlab program and script files always have filenames ending with ".m"; the programming language is exceptionally straightforward since almost every data object is assumed to be an array. Graphical output is available to supplement numerical results. How to use “help” command: help help Use help to see available commands/toolboxes help help fft helpdesk doc fft2 What version do I use? ‘ver’ to see the complete version information, whereas ‘version’ the short one. ver version Know what workspace is, how to see variables in the current workspace: a=10 % If you don’t define it, then matlab assumes it as a double. whos % List current variables, long form. who % Lists the variables in the current workspace. clear % clear variables in the workspace./Clear function in the memory. clear a* % clear all variables starting with “a”. help . % Operators and special characters. help punct % Punctuation / Zeichensetzung . Decimal point. 325/100, 3.25 and .325e1 are all the same. . Array operations. Element-by-element operations. . Field access. .. Parent directory. ex: cd .. ... Continuation. ex: p=3.1415926535897932384626433832795... +2; is equal to: p=3.1415926535897932384626433832795+2; , % Comma. The comma is used to separate matrix subscripts % and arguments to functions. % ex: A=rand(2,3); function m=myfun(a,b,c); ; % Semicolon: to suppress printing and to separate rows; % ex: a=3; a=[1 2 3;4 5 6] % Percent: comments. ! % Exclamation point: to execute operating system commands. % ex: !copy file1 file2 ’ % Transpose and string quoting. a=[1:5] a’ b=’b is a string’ = % Assigment / Zuweisung ^ % Power / Potenz % ex: 2^3 2^0.5 % is equal to sqrt(2) Data types: Help-> Matlab-> Programming-> Data type-> Overview or >>doc datatypes 15 data types. a=20; % a is assigned automatically as a ‘double’. a=int16(a); % convert a to 16-bit integer. a=cell(1); % build a cell. % build a structure: ‘field name’,field value. s = struct('type',{'big','little'},'color','red','x',{3 4}) ans % result saved always in. Normally, the variable will be defined automatically as a local variable. If you want to define a global variable, use “global”: global a1 a2; a1=10; whos To see the (extended) ASCII code: int8(‘abc’) % or int8 abc int16 € char(8364) The usage of ‘;’ p=30; -- The result will be shown in the workspace. p=30 -- The result will not be shown in the workspace but be saved in ‘ans’. ‘:’ a=[1:5] % construct a row vector, overwrite the previous definition. %or a=(1:5) a=[1:5]’ % construct a column vector. (transpose) b=a(:) % convert vector “a” to a column vector. a=zeros(5,6); % build a matrix with all elements as 0. b=ones(6,3); % build a “one” matrix. c=rand(3,2); % build a random matrix. d=rand(5,6,2); % build a 3D matrix. e=rand(M,N,P,...); % build a multi-dimensional matrix. Inner product: (scalar product) a=[2 4 6]; b=[3 5 7]; a*b’ Outer product: a’*b vector product: cross(a,b) or cross(b,a) Matrix index: The first term indicates row number and the second one indicates the column number. c(1,2) Any vector or matrix indication starts from 1, not 0. c(0,0) % Error example Select one column vector from a matrix: c=d(:,2,1) Select one sub-matrix from a matrix: c=d(1:3,2:4,2) [ ] Brackets are used in forming vectors and matrices. a=[]; for i=1:10, a=[a i]; end; How to find the index of a certain value in an array/a matrix? A=randn(5); [i,j]=find(A>0); Vector and matrix computation: Any variable can be directly used without definition if it is NOT defined before. If it is defined before, and if you want to change its size or data type, then you have to clear it or redefine it before you use it. for i=1:5, for j=1:6, d(i,j)=i*j; end; end; Inverse a matrix: inv(A) Without definition: for i=1:10; d(i)=i; end; If d is defined, and if you want to change the data type, you have to clear it firstly. clear d; for i=1:10; d{i}=’s’;end; real and imaginary (FFT) “i” is reserved for imaginary if you do not define it as others. clear i; a=3+7i; real(a) imag(a) % obtain the real part from a % obtain the imaginary part from a. a=[1:5]; b=[6:10]; a+b % vector addition a*b’ % inner product a.*b % Array multiply a./b % left array divide a.\b % right array divide Array multiply has two ways: for i=1:5, c(i)=a(i)*b(i); end; c=a.*b % this one is quicker and more efficient. Important: One has to write the programs (in Matlab) as many as possible to use array/matrix computation instead of “for” loop. “for” loop is used only when it cannot be programmed as array/matrix computation, this is because for loop or if statement will influence the computing efficiency. “for” and “while” for i=1:5, for j=1:5, A(i,j)=i+j; end; end; p=1; while p<5, p=p+1 end; “if”, “else”, and “elseif” IF expression statements ELSEIF expression statements ELSE statements END The expression is usually of the form expr rop expr, where rop is ==, <, >, <=, >=, or ~=. expr: expression. rop: relational operator. Ex: for i=1:5, for j=1:5, if i==j, A(i,j)=i*j; elseif i>j, A(i,j)=i; else A(i,j)=-j; end; end; end; Relational operators and logical operators see: help relop How to create and handle a figure? Create a figure window: figure; % you let the system give a figure number automatically. or figure(1); % you can give a figure number in the parenthesis. h=figure(2); % you get a figure handle number and save it in h. Close a figure by command: close; % close current figure. close(1) % close figure 1. close all % close all figures. Get the current figure handle: h1=gcf % Get Current Figure. (gcf) Get Object (figures, axes, …) properties: get(h1) Set Object properties: pos=get(h1,'position') Note: pos= [x y width height] where (x,y) is the coordinate of the figure (left-bottom corner) on the screen. pos(3)=100; set(h1,'position',pos); How to prevent a figure closed unintentionally? set(h1,'closerequestfcn',''); Recover it by: set(h1,'closerequestfcn','closereq'); Show an array in a figure: t=[0:0.01:2*pi]; p=sin(t); figure; plot(p); Use “subplot”: q=cos(t); figure; subplot(2,1,1); plot(p); subplot(212); plot(q); Use “hold”: figure; plot(p); hold on; plot(q,’r’); Text display format long g pi*1000 Show a matrix/image in a figure: for i=1:30, for j=1:30, A(i,j)=sin(i/15*pi)* cos(j/15*pi); end; end; figure; mesh(A); figure; imshow(A,[]); Show two images (with different colormaps) in a figure: load trees ‘load’ command will then return the image to ‘X’ and the colormap to ‘map’ automatically. (However, this is a special case!) Or you can give it by yourself: [X1,map1]=imread(‘trees.tif’); Question: What is ‘trees’? Where can I find it? In matlab there are some existed image files that one can use them. Some are saved in Matlabm_main_path\toolbox\images\imdemos\ Or, if you know the filename, you can use ‘which’ to find them out: which trees.tif Now you have another image which has different colormap: [X2,map2]=imread(‘kids.tif’); You want to put them together: figure; subplot(121); imshow(X1,map1); subplot(122); imshow(X2,map2); You will find that the colormap can not be used in the same figure. The ‘subimage’ can convert them to true color for display purposes: figure; subplot(121); subimage(X1,map1); subplot(122); subimage(X2,map2); How to read and write an image file and show it in a figure: R=imread(‘file1.bmp’,’bmp’); figure; imshow(R); If the matrix “R” has RGB-channel, then you can read only red channel by Red=R(:,:,1); If the matrix is in “char”, then you can show the matrix directly. imshow(R); If the matrix is in “double”, then you can show it by imshow(Red,[]); More see: help imshow. imwrite(A,’file2.bmp’,’bmp’); Frequently, we got an error in writing an image file. ex: A=[0:255]; A=repmat(A,50,1); imwrite(A,’file1.bmp’,’bmp’); R=imread(‘file1.bmp’); figure; imshow(R); Then we got an empty image in R. Why? The reason is that “A” is in double precision. We have to convert “A” to “char”: A=uint8(A); Then write “A” into a file. Load image from internet: A=imread(‘http://cvpr.unimuenster.de/teaching/ws06/bildverarbeitungWS06/download/Eisberg.jpg’); How to write a matlab *.m program. Use editor: function m=myfun(n); for j=1:5, m=j*n; end; Some frequently used computing commands: sum, prod, max, min, mean, std, mean2, std2, Range images R=double(imread(‘Tiefenbild1.gif’)); % anzeigen Obj=surf(R); colorbar; set(Obj,’Linestyle’,’none’); % to delete the meshgrids mesh(R); colorbar; Practices: Write your own functions and compare your results with the ones from matlab functions. 1. Write a program to synthesize a 1D and 2D Gaussian function by given values (mean=0, std=2, and the range=[-7,7]). Plot it in a figure. (Do not call gaussmf or other matlab functions) 2. Write a program to implement the function defined after and plot it on the figure. y=x^2+50*sin(x) for x=[-10:10], step of x is 0.1.