You are on page 1of 7

Matlab key

Matlab = MATrix LABoratory, a numerical computing environment. All variables are matrices. A scalar is a 1 x 1 matrix. Vectors are 1 x n or m x 1 matrices. Matlab is very fast in matrix operations, slow in heavy calculations (especially if many for-loops are used). Matlab includes many inbuilt functions and operations that can be used in calculation. Tip: Whenever possible try to use matrix operations instead of multiple looping.

Commands
Commands can be given either directly in the command window or by running a Matlab program or function. Programs or functions can be built and edited in Matlabs own text editor. Tip: Writing program files or function for long command lines or series makes re-editing and correcting faster and easier. Matlab commands and variable names are case sensitive.

Getting help
Simply write >>help command in the command window. For example >>help plot gives you a description of how command plot works. To find commands you can use the Matlab Help menu or search in the internet.

Simple calculations
Matlab can be used as a calculator. For example >> 438+127.2

ans = 565.2000 >> 25/3 ans = 8.3333 >> 1.1^200 ans = 1.8991e+08 Results can be presented either in short (16 bits) or long (32 bits) format. To change format you can type >>format short or >>format long in the command window.

Variables
Variables can be either inserted in the command window or read from a file. Inserting >> a=1 a= 1 >> b=[1 2;3 4] b= 1 3 2 4

>> c=[b;5 6] c= 1 3 5 2 4 6

The form of the matrix is controlled by using ; (semicolon). A semicolon in the end of a command row makes the answer invisible. >> c=[b;5 6]; >> You can also create vectors or matrices of certain sizes or contents. For example >> d=[1:1:5] d= 1 Or >> e=ones(1,5) e= 1 1 1 1 1 2 3 4 5

Other commands zeros: zero matrix eye: identity matrix rand: evenly distributed random numbers randn: normally distributed random numbers Reading from a file >> variable=load(file.dat,-ascii) reads the contents of a text file file.dat to a martix variable variable Make sure that the file file.dat is in the directory you are using. Otherwise you have to give the whole directory path before the file name. For changing directory use command >>cd >> save(file.dat,-ascii) saves the variables into a text file file. You can also give the variables you want to save as parameters >> save(file.dat,variable1,variable2,ascii) parameter -double saves the variables with double precision If you omit -ascii parameter Matlab saves the file in Matlab binary format and it cannot be opened using any other program.

You can also save the whole Matlab workspace (including all the variables and operations as you were using them). >> save filename saves the workspace in a file called filename.mat. You can open the file next time by typing >> load filename. Typing >>open filename.mat show all the variables in the command window, but does not load them for further use.

Constant variables
pi = i = j = (-1) inf = ans = the result of the latest calculation NaN = not a number

Basic operations for matrices


Adding and subtracting + and element by element. Same for both matrices and arrays. Matrices have to be of same size. Dividing and multiplying / and * matrix operations. Any scalar (a 1-by-1 matrix) may multiply anything. Otherwise, if calculating X*Y the number of columns of X must equal the number of rows of Y. ./ and .* array operations element by element. Matrices have to be of same size. ^ matrix power. .^ array power element by element. Martix manipulations >> a=c inserts the transpose of matrix c to a variable a. >> r=c(1,:); inserts the first row of matrix c into a variable r. >> rr=c(:,2); inserts the second column of matrix c into a variable rr. >>ra=c(:,:); is the same as >>ra=c; which inserts all the elements of matrix c into a variable ra. If a variable c was an n x m matrix, command >>reshape(c, 1, n*m); reshapes the matrix c to a vector of one row with n*m elements. When using reshape the total number of elements in a matrix has to remain constant.

>>size(c) gives the size of the matrix c. >>length(c) gives the length of the columns or rows, which ever is longer in matrix c. >>find(c>0) gives the indices of the elements of matrix c that are larger than 0. This is a very useful command and with it you can avoid several for-loops. >>mean(x) calculates the average or mean value of a vector x. For matrices mean(x) is a row vector containing the mean value of each column. >>sum(x) calculates the sum of the elements of a vector x. For matrices sum(x) is a row vector containing the sum of each column. For the above two and some other commands you find equivalents that omit non-number values in the matrix (nan-prefix). For example >>nanmean(x) calculates the mean of the columns of matrix x treating NaNs as missing values. Special operations Functions isnan, isinf and isfinite are so called True or False functions. They return a 1 or 0 depending on whether the statement is true or false. For example >>f=find(isnan(c)==0); stores the indices of the numeric elements (not NaNs) of matrix c in variable f.

Functions
Matlab has a comprehensive library of elementary mathematical functions. Triginometric: sin, acos, tanh etc. Exponential: ^, exp, log, log10, sqrt etc. Complex: real, imag, conj etc. Rounding: floor, round, ceil, fix, mod etc. Functions are called by typing the function name in the command window with required parameters. For example >>a=sin(pi/2); inserts the result of the function sin with a parameter pi/2 into a variable called a. You can also build your own functions and use normal if and for structures. See instructions in Matlab Help or type >>help function.

There is also a wide range of Matlab functions for different tasks available via the internet. Tip: If your task is complicated, it might be worth while searching whether someone has published something similar (if not the correct solution) in the internet. Example of a function With the following m-file (edited and saved in the text editor) you can calculate the test value for students t-test to test the statistical significance of a difference in for example sample means. The script is as follows: function t=ttest(data1, data2) x1=nanmean(data1); x2=nanmean(data2); s1=nanstd(data1); s2=nanstd(data2); n1=length(find(isnan(data1)==0)); n2=length(find(isnan(data2)==0)); t=(x1-x2)/sqrt((n1-1)*s1^2+(n2-1)*s2^2)*sqrt((n1+n2-2)/(1/n1+1/n2)) In the command window you would call the function >> ttest(1:1:5,1:2:10); t= -1.264911064067352e+000 Note the semicolons in the end of each line except the last. Now the result of the function (the value of t) is printed on the command window after each calculation.

Graphics
Matlab has several functions for making graphs. Command >>plot(x,y) plots vector y as a function of vector x. The length of the vectors has to be the same. Command >>plot(x) plots vector x as a function of the indices of the vector. Command plot draws the figure in a separate figure window. If no windows are open it creates a new window. Otherwise, the graph is drawn into the window that was used latest.

Command >>figure creates a new figure window and command >>clf clears the active graph window. The appearance of the figure can be controlled by either giving parameters to the command plot or by selecting the properties from the graphical interface. Command >>plot(x,y,k.) plots the data points as black dots. For more detailed information see >>help plot Command >>hold on retains the existing plot and you can plot a second line on the same figure as the previous. >>hold off releases this state. The x-and y-axis can be labeled using commands >>xlabel(x-value) and >>ylabel(yvalue), respectively. Similarly a title can be added by >>title(title) and a legend by >>legend. Command >>grid on creates gridlines to the figure and command >> axis([xmin xmax ymin ymax]) sets the x and y limits for the axis. Command >>bar plots a bar figure and with semilogx, semilogy and loglog you get plots in logarithmic scales. All these manipulations can also be made using the mouse in a graphical interface. In the command window manipulations can be made with commands get and set. >>get(gca) lists all the features of the latest figure and >>set(gca,xlim,[0 10]) sets the minimum and maximum limits of the x-axis of the latest figure to 0 and 10. With command subplot you can plot several figures in the same window and plotyy creates a figure with two y-axes, one on each side of the graph.

Other useful commands


>>clear Clears the working memory and all the variables are erased. If you use the same names for variables, Matlab does not empty the previous variable but writes over it. If your first variable called a has more elements than the next you call a and you dont clear it, the new a will contain the remainders of the previous a. >>close Closes all the open figure windows >>who Lists all the variables currently in the working memory.

You might also like