Vous êtes sur la page 1sur 6

Getting started with MATLAB

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Introduction to Matlab % This course is adapted from MIT, Stanford, U Delaware Matlab crash % courses. % I have used the documents written by Stefan Roth and Tobin Driscoll % besides the Matlab online tutorial. Azadeh Samadani 01/10/2007 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Useful links: The Getting Started with MATLAB manual is a very good place to get a more gentle and thorough introduction: http://www.mathworks.com/access/helpdesk/help/techdoc/learn_matlab/ http://www.mathworks.com/academia/student_center/tutorials/

Basics:
If you type in a valid expression and press Enter, MATLAB will immediately execute it and return the result, just like a calculator. >> 2+2 ans = >> 42 ans =

16

>> sin(pi/2) ans = 1 >> 1/0 Warning: Divide by zero. ans = Inf >> exp(i*pi) ans = -1.0000 + 0.0000i Notice some of the special expressions here: pi for , Inf for , and i for 1 . Another special value is NaN, which stands for not a number. NaN is used to express an undefined value. For example, >> Inf/Inf ans = NaN

* Challenge: Calculate the following statements: >>help exp). Here are a few other demonstration statements. % % x = rand(2,2); % s = Hello world; % t = 1 + 2 + 3 + ... %

= 1+ 5

and

sin 1 (1 / 2) and tan(e) (Hint:

Anything after a % sign is a comment. ; means "dont print out result" single quotes enclose a string ... means continue a line

4 + 5 + 6 % ... Here are a few useful commands: who cd pwd dir ls * Type why in your command window % % % % % gives you your variables Change current working directory. Show (print) current working directory. List directory. List directory.

Creating matrices and vectors


A = [1 2; 3 4]; B = [1,2; 3,4]; % % % % % % % % % % % % % % Creates a 2x2 matrix The simplest way to create a matrix is to list its entries in square brackets. The ";" symbol separates rows; the (optional) "," separates columns. A scalar A row vector A column vector Transpose a vector (row to column or column to row) A vector filled in a specified range: [start:stepsize:end], brackets are optional Empty vector

N v v v

= = = =

5 [1 0 0] [1; 2; 3] v'

v = 1:0.5:3 v = pi*[-4:4]/4 v = []

Creating special matrices


1ST parameter is ROWS, 2ND parameter is COLS m v m v = = = = zeros(2, 3) ones(1, 3) eye(3) rand(3, 1) % % % % % % Creates a 2x3 matrix of zeros Creates a 1x3 matrix (row vector)of ones Identity matrix (3x3) Randomly filled 3x1 matrix (column vector); see also randn Creates a 3x3 matrix (!) of zeros

m = zeros(3)

* Challenge: Without using a for loop, make a 4x4 matrix with zeros in lower left triangle and ones in upper right triangle (Hint: >>doc triu, >>doc tril). Then find the size of the matrix, number of dimensions and its nonzero elements. (Hint: >>doc size, >>doc ndims, >>doc find) * Challenge: Create a 3x1 matrix with random elements between 0 and 5. (Hint: >>doc rand) * Challenge: Create random nxn symmetric and antisymmetric matrices. (symmetric: a = transpose(a). antisymmetric: a = -transpose(a) ) * Challenge: Without using a for loop, create the 5x5 matrix A = [1 2 3 4 5; 6 7 8 9 10; 11].(Hint: >>doc reshape) * Challenge: Find the row-wise sum of the elements of A. Find the column-wise product of the elements of A. (Hint: >>doc sum)

Indexing vectors and matrices


% Warning: Indices always start at 1 and *NOT* at 0! v = [1 2 3]; v(3) % Access a vector element

m = [1 2 3 4; 5 7 8 8, 9 10 11 12; 13 14 15 16] m(1, 3) % Access a matrix element % matrix(ROW #, COLUMN #) m(2, :) % Access a whole matrix row (2nd row) m(:, 1) % Access a whole matrix column(1st column) m(1, 1:3) % Access elements 1 through 3 of the 1st % row m(2:3, 2) % Access elements 2 through 3 of the % 2nd column m(2:end, 3) % Keyword "end" accesses the remainder of % a column or row m = [1 2 3; 4 5 6] size(m) % Returns the size of a matrix size(m, 1) % Number of rows size(m, 2) % Number of columns m1 = zeros(size(m)) % Create a new matrix with the size of m

*Challenge: Create a 5x3 matrix with random elements and access the (3x2) elements on the lower right hand corner. (Hint: >>help end) Remember to check the help system often! It is really easy! If you know the command that you want to obtain some info about it is as easy as typing help command where command is the command that you are interested in.

Simple operations and the dot modifier


a 2 a b a a a a = [1 2 3 4]'; * a / 4 = [5 6 7 8]'; + b - b .^ 2 .* b % % % % % % % % % % A column vector Scalar multiplication Scalar division Another column vector Vector addition Vector subtraction Element-wise squaring (note the ".") Element-wise multiplication (note the ".") Element-wise division (note the ".")

a ./ b

* Challenge: Define two arbitrary vectors A and B with same dimensions. Calculate A*B, A.*B and A*B? What is the answer to A/B and A./B? Which operations do not make sense?

Vector operations
% Built-in Matlab functions that operate on vectors sum(a) mean(a) std(a) % Sum of vector elements % Mean of vector elements % Standard deviation

max(a) min(a)

% Maximum % Minimum

* Challenge: Without using a for loop, calculate the sum of all prime numbers less than 100. (Hint:>>help isprime) % If a matrix is given, then these functions will operate on each column of the matrix and return a row vector as result a = [1 2 3; 4 5 6] mean(a) max(a) max(max(a)) % % % % A matrix Mean of each column Max of each column Obtaining the max of a matrix

Graphics (2D plotting)


x = [0 1 2 3 4]; plot(x); pause plot(x, 2*x); axis([0 4 0 8]); figure; x = pi*[-24:24]/24; plot(x, sin(x)); xlabel('radians'); ylabel('sin value'); title('dummy'); figure; subplot(1, 2, 1); plot(x, sin(x)); axis square; subplot(1, 2, 2); plot(x, 2*cos(x)); axis square; figure; plot(x, sin(x)); hold on; plot(x, 2*cos(x), '--'); legend('sin', 'cos'); hold off; figure; m = rand(64,64); imagesc(m) %colormap gray; axis image; axis off; % % % % % Basic plotting Plot x versus its index values Wait for key press Plot 2*x versus x Adjust visible rectangle

% Open new figure % Assign label for x-axis % Assign label for y-axis % Assign plot title % Multiple functions in separate graphs % (see "help subplot") % Make visible area square

% % % % % % % % %

Multiple functions in single graph '--' chooses different line pattern Assigns names to each plot Stop putting multiple figures in current graph Plot matrix as image Choose gray level colormap Show pixel coordinates as axes Remove axes

%You may zoom in to particular portions of a plot by clicking on the %magnifying glass icon in the figure and drawing a rectangle. * Challenge: Plot functions x (blue squares and line), x^2 (red circles and line) and x^1/2 (green diamonds and line) between (0,2) on the same plot.

Lets do Exercise 1!

Creating scripts and functions using m-files


% % % % % Matlab scripts are files with ".m" extension containing Matlab commands. Variables in a script file are global and will change the value of variables of the same name in the environment of the current Matlab session. A script with name "script1.m" can be invoked by typing "script1" in the command window.

* Challenge: Create a script called myfirstscript.m to prints out todays date. (Hint: >>help date) % % % % % % % % Functions are also m-files. The first line in a function file must be of this form: function [out_1,..., out_m] = myfunction(in_1,..., in_n) The function name should be the same as that of the file (i.e. function "myfunction" should be saved in file "myfunction.m"). Have a look at myfunction.m for examples. % Global variable a % Call myfunction which has local % variable a

a = [1 2 3 4]; b = myfunction(2 * a) >>a

function y = myfunction(x) % Function of one argument with one return value a = [-2 -1 0 1]; % Have a global variable of the same name y = a + x; >>help myfunction % % % % % % Functions are executed using local workspaces: there is no risk of conflicts with the variables in the main workspace. At the end of a function execution only the output arguments will be visible in the main workspace. If we create a file named f.m in the current working directory with this code

%f.m function y = f(x, a) % Returns the square of the first argument times the second y = a * x ^ 2; % Then, from the command window we can just evaluate the function f(3, 4) ans = 36 % In the command window type: >>help f * Challenge: Define a new function called stat.m that calculates the mean and standard deviation of a vector x.

* Challenge: Define a new function called bellcurve.m that creates 10000 normally distributed random numbers with mean 3 and standard deviation 2. Make a histogram to verify the bell curve. (Hint:>> help randn and >>help hist) Time for Exercise 2 and 3!

Syntax of flow control statements (for, while and if expressions)


% % % % % % % % % % % % % % % % % % % % % % % % % for VARIABLE = EXPR STATEMENT ... STATEMENT end EXPR is a vector here, e.g. 1:10 or -1:0.5:1 or [1 4 7] while EXPRESSION STATEMENTS end if EXPRESSION STATEMENTS elseif EXPRESSION STATEMENTS else STATEMENTS end (elseif and else clauses are optional, the "end" is required) EXPRESSIONs are usually made of relational clauses, e.g. a < b The operators are <, >, <=, >=, ==, ~=(almost like in C(++))

* Challenge: Write a function that takes two variables and prints a statement indicating whether the first variable is smaller, larger, or equal to the second variable. * Challenge: Write a function that calculates

(n
0

200

+ n2 )

Vous aimerez peut-être aussi