1

Get Started in MATLAB (Math 3090 F 2004)

The best way to learn MATLAB is by trying it yourself. Here, we give you a quick tour and hope it will give you a sense how MATLAB operates and get you start to use it for the course.

1. Common properties in Matlab

·  To enter MATLAB, click “start”, choose “programming files”, and select “MATLAB 7.0” from the menu.

·  Once entered to MATLAB, type your commands after the MATLAB prompt, , in the command window.

·  Case sensitive, i.e., n and N are different variables

·  Typing the name of the variable or type the name with a “,” displays its current value

·  A semicolon at the end of a command suppresses the screen output

·  The up and down arrows can be used to scroll through your previous commands. Also, an old command can be recalled by typing the first few characters followed by up arrow

·  Comment line starts with %

·  Type help topic to access online help on the command, function or symbol topic. Eg., help sqrt

·  Type lookfor keyword to search for functions related to the keyword, eg., lookfor plot

·  Type clear x to clear the variable x from the workspace, while clear or clear all will erase all the existing variables in the workspace

·  Type exit or quit to quit MATLAB

2. Numbers and Arithmetic Express

Here are some examples of legal numbers in MATLAB:

3 -99 0.0001

9.6397238 1.60210E-20 6.022332e23

2i -3.14159i 3e5i

You can build expression with the usual arithmetic operators and precedence rules:

+ addition

- subtraction

* multiplication

/ right division

\ left division

^ power

MATLAB provides the elementary mathematical functions as build-in functions. These functions include abs, sqrt, log, sin, and atan, etc. You can also add your own functions with M-files.

% It also defines some commonly used

% special values like Pi. Try the following:

> a = pi

> b = 4 * atan(1)

> a-b

% MATLAB allows complex numbers, indicated by

% the special functions i and j.

> z = 3 + 4*i,

> r = abs(z), % complex magnitude

> theta = angle(z), % the phase angle

> w = r * exp(i*theta)

The build-in function i can also be a variable. When used as a variable previously, then i becomes unavailable within the current workspace until the variable is cleared.

% Another way to avoid such a problem and define the complex value is

> ii = sqrt(-1)

> z = 3 + 4 * ii

Division by zero does not lead to an error condition or termination of execution in Matlab. Try

> s = 1/0

% which result in

% Warning: Divide by Zero

% s =

% Inf % means infinity

3. Output Format

You can use format command to control the numeric display format.

> x = [4/3, 1, 1.2345e-6]

> format short

> x

> format short e

> x

> format long

> x

> format long e

> x

> format bank

> x

> format hex

> x

> format short

4. Vector, Matrix, and their operations

> A = [2 1 0; 1 3 1; 0 1 2]

> b = [10:12]

> A = [A; b]

% You can extract small matrices from large matrices using : (a colon)

> B = A(1:2, :) % a colon with any beginning or ending value means all

> C = A(:, 1:2)

> D = A(1:3, 1)

> At = A’ % transpose matrix A

> A = A(1:3, 1:3); % take a 3 by 3 sub-matrix from A

> invA = inv(A) % inverse of A

% adding and subtracting matrices

> C = A + A’

> x = [1 2 3]

> y = x’ – 1

% multiplying matrices

% inner (or dot) product

> z1 = x*y

% outer product

> z2 = y*x

% matrix and scalar product

> C = 2 * A

% matrix and vector product

> b = A*x’

% Dividing matrices

% X = A\B is a solution to A*X = B

% X = B/A is a solution to X*A = B

% For example,

> sol_right = A\b

> b = x*A

> sol_left = b/A

% matrix functions

> det(A) % determinant

> trace(A) % trace

> kron(A) % Kronecker product

> norm(A, 2) % matrix 2-norm

> help norm % for more details

% other ways to generate a vector of consecutive numbers

> x = [1:5] % generate a vector of numbers from 1 to 5 with unit

% increments

> y = 0:pi/4:pi % with increments pi/4

> z = pi:-pi/4:0 % with negative increments

> v = sin(y) % combined with functions

% pointwise (element-by-element) operations

> w1 = x .*v

> w2 = x./v

> w3 = x.^2

% special matrices

> x =[] % empty matrix

> x = zeros(3, 3) % zero matrix of size 3 by 3

> x = ones(3, 3) % all one matrix

> x = eye(3, 3) % identity matrix

> y = rand(3) % random matrix with uniform distribution

> z = randn(3, 3) % random matrix with normal distribution

% manipulating matrices

% rot90 – rotation

% fliplr – flip matrix left-to-right

% flipup – flip matrix up-and-down

% diag – extract or create diagonal

% tril – lower triangular part

% triu – upper triangular part

% reshape – reshape the maxtrix

% : - general arrangment of matrix elements

% You can try yourself. Here, I provides a few examples

> A = 1:12

> B = reshape(A, 3, 4)

> tril(B)

5. Writing M-files

MATLAB is usually used in a command-driven mode; when you enter single-line commands, MATLAB processes them immediately and displays the results. MATLAB can also execute sequences of commands that are stored in .m files, called M-files.

An M-file consists of a sequence of normal MATLAB statements, which possibly include references to other M-files. Two types of M-files can be used: scripts and functions. Scripts, automate long sequences of commands. Functions, provide extensibility to MATLAB. They allow you to add new functions to the existing functions.

Both scripts and functions are ordinary ASCII text files. To access the embedded ASCII text file editor in MATLAB, go to “file”, select “ new” and then choose “M-files” to create a new M-file, or select “open” to open an existing M-file.

Script files or scripts

Type the following file into your directory and save it as “fofdh.m”. And we will use it as an example.

% Name: fofdh.m

% This MATLAB code is for the first order finite difference algorithm.

% It is applied to Newton's law of cooling model.

% setting up the parameters

n = 300; % Number of Time Steps

h = 1; % Time step size

y_sur = 70; % room (surrounding) temperature

% initializing the time and coffee temperature arrays

y = zeros(n+1,1); % set up a coffee temperature column array of size n+1

y(1) = 200; % initial temperature

t = zeros(n+1,1); % set up a time column array of size n+1

% estimating the parameter c, insulation ability of the cup

h_obser = 5; % time of observing the coffee temperature

y_obser = 100; % observed coffeed temperature at time h_obser

c = (y_obser - y(1))/(h_obser * (y_sur - y(1)));

% calculating parameters a and b

a = 1-c*h;

b = c*h*y_sur;

% iteratively calculate the coffee temperature

for k = 1:n,

y(k+1) = a*y(k) + b;

t(k+1) = t(k) + h;

end

% display the result

plot(t,y);

In MATLAB command window, do the following

> clear % erase all the existing variables

> fofdh % execute the file fofdh.m

Function files or function

An M-file that contains the word function at the beginning of the first line is a function file. A function differs from a script in that arguments may be passed, and variables defined and manipulated inside the file are local to the function and don’t operate globally on the workspace.

Let us change the existing file fofdh.m into a function file. Open fofdh.m and save it as coffeeTemperature.m.

function [t, y] = coffeeTemperature(h, n)

% Name: coffeeTemperature.m

% This MATLAB code is a function file, which is applied to Newton's law of

% cooling model.

%

% Input:

% h – scalar, time step size

% n – scalar the number of total iterations or time steps

% Output:

% t – an array of size n+1; it contains the time points at which

% the temperature predictions occurs

% y – an array of size n+1; it contains the values of coffee temperatures

% setting up the parameters

y_sur = 70; % room (surrounding) temperature

% initializing the time and coffee temperature arrays

y = zeros(n+1,1); % set up a coffee temperature column array of size n+1

y(1) = 200; % initial temperature

t = zeros(n+1,1); % set up a time column array of size n+1

% estimating the parameter c, insulation ability of the cup

h_obser = 5; % time of observing the coffee temperature

y_obser = 100; % observed coffeed temperature at time h_obser

c = (y_obser - y(1))/(h_obser * (y_sur - y(1)));

% calculating parameters a and b

a = 1-c*h;

b = c*h*y_sur;

% iteratively calculate the coffee temperature

for k = 1:n,

y(k+1) = a*y(k) + b;

t(k+1) = t(k) + h;

end

In the MATLAB command window, type the following

> clear;

> h = 1;

> n = 300;

> [time, temp] = coffeeTemperature(h, n);

> plot(time,temp);

Or you can put all the above commands in a script file call main_coffee.m, namely

% Name: main_coffee.m

h = 1;

n = 300;

[time, temp] = coffeeTemperature(h, n);

plot(time,temp);

And then in the MATLAB command window, type the command:

> main_coffee

The advantages of doing so is to be able to save your time to type all the commands every time when you try out the same experiment with different values of parameters.

6. Graphics

2D Graphics:

Elements plotting functions

% plot creates a plot of vectors or columns of matrices

% loglog creates a plot using logarithmic scales for both axes

% semilogx creates a plot using a logarithmic scalars for the x-axi

% and a linear scale for y-axis

% semilogy creates a plot using a logarithmic scalars for the y-axi

% and a linear scale for x-axis

% You can add tiles, axis, labels, grid lines, and text to your graph using

% title adds title to the graph

% xlabel adds a label to the x-axis

% ylabel adds a label to the y-axis

% text displays a text string at a specific location

% gtext places text on the graph using the mouse

% grid turns on grid lines

% For examples

> t = 0:pi/100:2*pi;

> x = sin(t);

> y1 = sin(t+0.25);

> y2 = sin(t + .5);

> plot(x, y1, ‘r-‘); hold on;

> plot(x, y2, ‘g+’); hold off;

> figure(2); % open a new figure window labeled as 2

> plot(x, y1, ‘r-‘, x, y2, ‘g+’);

> title(‘Phase shift’);

> xlabel(‘x = sin(t)’)

> ylabel(‘y = sin(t+)’)

> gtext(‘y1’); gtext(‘y2’)

% you can also manipulate the figure by selecting each object from the

% “edit” menu from the figure window.

% Plotting multiple figures in one window

> figure(3);

> subplot(2, 1, 1), plot(x, y1);

> subplot(2, 1, 2), plot(x, y2);

3D Graphics:

Elements plotting functions

% plot3 - plots lines and points in 3-D

> figure(4)

> t = 0:pi/50:pi;

> plot3(sin(t), cos(t), t);

% mesh, meshgrid - create 3D perspective plots of the matrix elements

% displayed a heights above the underlying mesh grid.

> figure(5)

> x = -8:.5:8;

> y = x;

> [X, Y] = meshgrid(x, y);

> R = sqrt(X.^2 + Y.^2) + eps;

> Z = sin(R)./R;

> mesh(Z);

> surf(Z); % generates a colored faceted view of the surface

% contour, contour3 – create contour plots

> figure(6)

> contour(Z, 20)

> contour3(Z, 20)

> surfc(Z)

% image – display a matrix as an image by mapping the elements of the

% matrix to the current color map.

> figure(7)

> image(log10(Z+1));

> colormap(cool); % choose a color map

> axis equal; % set axis to equal

Hope this will get you started on MATLAB. It really can do lots of amazing things for you as you can find it out this winter. Enjoy using it!