Docstoc

Basic MATLAB

Document Sample
Basic MATLAB Powered By Docstoc
					                  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 =
         4

>> 4ˆ2
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:     1 5          and   sin 1 (1/ 2) and tan(e) (Hint:
                                                                 2
>>help exp).

Here are a few other demonstration statements.
%                                          %     Anything after a % sign is a comment.
x = rand(2,2);                             %     ; means "don’t print out result"
s = ’Hello world’;                         %     single quotes enclose a string
t = 1 + 2 + 3 + ...                        %     ... means continue a line
4 + 5 + 6 % ...

Here are a few useful commands:

who                                       %   gives you your variables
cd                                        %   Change current working directory.
pwd                                       %   Show (print) current working directory.
dir                                       %   List directory.
ls                                        %   List directory.

* Type why in your command window

Creating matrices and vectors
A = [1 2; 3 4];                           %   Creates a 2x2 matrix
B = [1,2; 3,4];                           %   The simplest way to create a matrix is
                                          %   to list its entries in square brackets.
                                          %   The ";" symbol separates rows;
                                          %   the (optional) "," separates columns.

N   =   5                                 %   A scalar
v   =   [1 0 0]                           %   A row vector
v   =   [1; 2; 3]                         %   A column vector
v   =   v'                                %   Transpose a vector (row to column or
                                          %   column to row)
v = 1:0.5:3                               %   A vector filled in a specified range:
v = pi*[-4:4]/4                           %   [start:stepsize:end], brackets are
                                          %   optional
v = []                                    %    Empty vector

Creating special matrices
1ST parameter is ROWS, 2ND parameter is COLS

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

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

* 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)                                    % Sum of vector elements
mean(a)                                   % Mean of vector elements
std(a)                                    % Standard deviation
max(a)                                     % Maximum
min(a)                                     % 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]                         %   A matrix
mean(a)                                    %   Mean of each column
max(a)                                     %   Max of each column
max(max(a))                                %   Obtaining the max of a matrix

Graphics (2D plotting)
x = [0 1 2 3 4];                           %   Basic plotting
plot(x);                                   %   Plot x versus its index values
pause                                      %   Wait for key press
plot(x, 2*x);                              %   Plot 2*x versus x
axis([0 4 0 8]);                           %   Adjust visible rectangle

figure;                                    % Open new figure
x = pi*[-24:24]/24;
plot(x, sin(x));
xlabel('radians');                         % Assign label for x-axis
ylabel('sin value');                       % Assign label for y-axis
title('dummy');                            % Assign plot title

figure;
subplot(1, 2, 1);                          % Multiple functions in separate graphs
plot(x, sin(x));                           % (see "help subplot")
axis square;                               % Make visible area square
subplot(1, 2, 2);
plot(x, 2*cos(x));
axis square;

figure;
plot(x, sin(x));
hold on;                                   %   Multiple functions in single graph
plot(x, 2*cos(x), '--');                   %   '--' chooses different line pattern
legend('sin', 'cos');                      %   Assigns names to each plot
hold off;                                  %   Stop putting multiple figures in current
                                           %   graph
figure;
m = rand(64,64);
imagesc(m)                                 %   Plot matrix as image
%colormap gray;                            %   Choose gray level colormap
axis image;                                %   Show pixel coordinates as axes
axis off;                                  %   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.
Let’s 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 today’s 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.
%

a = [1 2 3 4];                             % Global variable a
b = myfunction(2 * a)                      % Call myfunction which has local
                                           % variable 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.
                                                200
* Challenge: Write a function that calculates    (n
                                                0
                                                       3
                                                            n2 )

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:60
posted:3/6/2010
language:English
pages:6
Jun Wang Jun Wang Dr
About Some of Those documents come from internet for research purpose,if you have the copyrights of one of them,tell me by mail vixychina@gmail.com.Thank you!