Introduction to MATLAB
Getting Started with MATLAB
 To start MATLAB in Windows: double click the desktop MATLAB icon
 To start MATLAB in Linux: enter
matlab
at the system prompt
katana:~ % matlab
In either case, a MATLAB command window appears, along with a >> prompt. Start entering any valid MATLAB commands at >>. The first example below demonstrates the use of a MATLAB utility function called version
to query the current version of MATLAB you are using on this computer. Note that all typed characters to the right of the % symbol are is treated as comments or documentation for the line. Output, if any, appears immediately after the issuing of the command.
>> version % this tells you the running MATLAB version
ans =
7.12.0.635 (R2011a)
Throughout this tutorial, we will use this (%) inline comment feature to document the purposes of the commands. You should take advantage of this to document your own code wherever deemed appropriate to make clear your intentions for future reference.
>> help % lists available packages/toolboxes.
HELP topics:
matlab\general  General purpose commands.
matlab\ops  Operators and special characters.
matlab\lang  Programming language constructs.
matlab\elmat  Elementary matrices and matrix manipulation.
matlab\randfun  Random matrices and random streams.
matlab\elfun  Elementary math functions.
. . . . . .
. . . . . .
>> help elfun % lists elementary math functions
Elementary math functions.
Trigonometric.
sin  Sine.
sind  Sine of argument in degrees.
. . . .
>> help sin % if you know function name but not it's usage
SIN Sine of argument in radians.
SIN(X) is the sine of the elements of X.
. . .
>> lookfor cosine % if you don't know the function name
acos  Inverse cosine, result in radians.
acosd  Inverse cosine, result in degrees.
acosh  Inverse hyperbolic cosine.
cos  Cosine of argument in radians.
. . .
>> doc sin % spawns a new document window with details on sine
>> quit % quits MATLAB
Rules on Variable Names
 Names are case sensitive, e.g., NAME and Name are 2 distinct names.
 Variable names begin with a letter, e.g., A2z or a2z. On the other hand, 2Az is not valid
 Names can be a mix of letters, digits, and underscores (e.g., vector_A)
 Cannot use reserved characters: % = + . ~ ; : ! ‘ [ ] ( ) , @ # $ & ^
 Names can be up to 63 characters
Reserved Characters % = ; ,
Some characters are reserved by MATLAB for various purposes. Some are arithmetic or matrix operators:
=, +,  , *, / , \ and others are used to perform a multitude of operations. Reserved characters can not be used in variable, function, or file names.
>> % text after % until end of line treated as comments
>>
>> a = 3 % define a to have the value 3
a =
3
>> a = 3; % ; suppresses printing
>>
>> b = 4; c = 5; % ; delimits multiple commands on same line
>>
>> d = 6, e = 7; % , delimits commands but enables printing
d =
6
>> a#2=3 % illegal use of reserved character in variable name
??? a#2=3

Error: The input character is not valid in MATLAB statements or expressions.
Reserved Characters : [ ] ( )
>> x = 1:2:9 % define vector x with : operator (begin:interval:end)
x =
1 3 5 7 9
>> y = 3:5 % interval is defaulted to 1; same as y=[3:5]
y =
3 4 5
>> X = [1, 2, 3; 4, 5, 6] % 2D array.
% [ ] prevents ambiguity for arrays
% ; concatenates vertically (new row)
% , concatenates horizontally (new columns)
X =
1 2 3
4 5 6
>> X(2,3) % ( ) for subscripting; why ans ?
ans =
6
Reserved Characters ... and '
>> x = [1 2 3 ... % ... means to be continued
4 5 6]
x =
1 2 3 4 5 6
>> s = 'this is a character string'; % blanks preserved in quotes
>> x = [1 2 3]' % ' is transpose (e.g., turns row into column)
x =
1
2
3
>> X = [1 2 3; 4 5 6]; size(X) % size (dimensions) of X
ans =
2 3
>> X = [1 2 3; 4 5 6]; numel(X) % number of elements in X
ans =
6
Reserved Character ! (or system)
>> !dir % runs a dos command on Windows host
Volume in drive C has no label.
Volume Serial Number is 6860EA46
Directory of C:\Program Files\MATLAB704\work
01/31/2007 10:56 AM .
01/31/2007 10:56 AM ..
06/13/2006 12:09 PM 12 foo.exe
06/13/2006 08:57 AM 77 mkcopy.m
>> !ls l % runs a unix command on Linux host
total 0
rwrr 1 kadin scv 0 Jan 19 15:53 file1.m
rwrr 1 kadin scv 0 Jan 19 15:53 file2.m
rwrr 1 kadin scv 0 Jan 19 15:53 file3.m
>> system('ls l') % more general form; also unix('ls l')
Array operations
>> a = 1:3; % a is a row vector
>> b = 4:6; % b is a row vector
>> c = a + b % c has same shape as a & b
c =
5 7 9
>> A = [a;b] % combines rows to generate 2x3 matrix A
% what is the outcome of A=a;b ?
A =
1 2 3
4 5 6
>> B = A' % B is transpose of A
B =
1 4
2 5
3 6
Other ways to create B ? (hint: with a and b )
Matrix Operations
>> C = A*B % * is overloaded as matrix multiply operator
C =
14 32
32 77
>> D = A.*A % .* turns matrix multiply to elemental multiply
% i.e., D_{ij} = A_{ij}*A_{ij}; for all i and j
D =
1 4 9
16 25 36
>> E = A./A % elemental divide; E_{ij} = A_{ij}/A_{ij}
E =
1 1 1
1 1 1
>> who % list existing variables in workspace
Your variables are:
A B C D E a b d
Data Types
>> whos % detail listing of workspace variables
Name Size Bytes Class
A 2x3 48 double array
B 3x2 48 double array
C 2x2 32 double array
D 2x3 48 double array
E 2x3 48 double array
a 1x3 24 double array
b 1x3 24 double array
c 1x3 24 double array
Grand total is 37 elements using 296 bytes
>> A = single(A); % recast A to single data type to save memory
>> whos
Name Size Bytes Class
A 2x3 24 single array
. . . .
>> clear % delete all workspace variables
For Loops
for k=1:5 % use forloops to execute iterations / repetitions
for j=1:3
for i=1:4
a(i, j, k) = i + j + k;
end
end
end
Utilities to initialize or define arrays: ones, rand, eye, . . .
Trigonometric and hyperbolic functions : sin, cos, sqrt, exp, . . .
These utilities can be used on scalar or vector inputs . . .
>> a = sqrt(5); v = [1 2 3]; A = sqrt(v);
if Conditional
Scalar operation . . .
a = zeros(3);
b = zeros(3);
for j=1:3
for i=1:3
a(i,j) = rand; % use rand to generate a random number
if a(i,j) > 0.5
b(i,j) = 1;
end
end
end
Equivalent vector operations . . .
A = rand(3); % A is a 3x3 random number double array
B = zeros(3); % Initialize B as a 3x3 array of zeroes
B(A > 0.5) = 1; % set B(i,j) to 1 if corresponding A(i,j) > 0.5
Elemental Matrix Division
The purpose is to compute elemental division with the denominator matrix having zeroes. For those situations, c
is to be set to 0.
Scalar form . . .
a = rand(4,3); b = rand(size(a)); c = zeros(size(b));
b(1,3) = 0; b(3,2) = 0;
for j=1:3
for i=1,4
if (b(i,j) ~= 0) then
c(i,j) = a(i,j)/b(i,j);
end
end
end
Equivalent vector form . . .
e = b~=0 % e is a logical array
e =
1 1 0
1 1 1
1 0 1
1 1 1
c(e) = a(e)./b(e) % c = 0 ∀ b = 0
c =
0.9768 1.4940 0
2.3896 0.4487 0.0943
0.7821 0 0.2180
11.3867 0.0400 1.2741
In the above, e
is a logical array and is used throughout the statement to avoid matlab dropping those elements that equal zero and hence make the equation's arrays with unmatched sizes. If c is not preallocated as 2D (with zeros), the operation
still works, but c would be a 1D array.
Cell Arrays
A cell array is a special array of arrays. Each element of the cell array may point to a scalar,
an array, or another cell array.
>> C = cell(2, 3); % create 2x3 empty cell array
>> M = magic(2);
>> a = 1:3; b = [4;5;6]; s = 'This is a string.';
>> C{1,1} = M; C{1,2} = a; C{2,1} = b; C{2,2} = s; C{1,3} = {1};
C =
[2x2 double] [1x3 double] {1x1 cell}
[2x1 double] 'This is a string.' []
>> C{1,1} % prints contents of a specific cell element
ans =
1 3
4 2
>> C(1,:) % prints first row of cell array C; not its content
Related utilities: iscell, cell2mat
Structures
Ideal layout for grouping arrays that are related.
>> employee(1).last = 'Smith'; employee(2).last = 'Hess';
>> employee(1).first = 'Mary'; employee(2).first = 'Robert';
>> employee(1).sex = 'female'; employee(2).sex = 'male';
>> employee(1).age = 45; employee(2).age = 50;
>> employee(2) % list contents of employee 2
ans =
last: 'Hess'
first: 'Robert'
sex: 'male'
age: 50
>> employee(:).last % display last name of all employees
ans =
Smith
ans =
Hess
To avoid seeing "ans", you can save the content to a variable first. Note however that because the last names vary in byte size, the variable should be a cell array.
>> a = {employee(:).last} % a = employee(:).last would fail
a =
'Smith' 'Hess'
Alternative style:
>> employee = struct('last',{'Smith','Hess'}, 'first',{'Mary','Robert'},
'sex',{'female','male'}, 'age',{45,50});
Related utilities: isstruct, fieldnames, getfield, isfield
File Types
There are many types of files in MATLAB :
 script mfiles (.m)  group of commands; reside in the same workspace from which it is invoked
 function mfiles (.m)  memory access controlled; parameters passed as input, output arguments; reside in own workspace
 mat files (.mat)  binary (or text) files handled with save and load
 mex files (.mex)  runs C/FORTRAN codes from mfile
 eng files (.eng)  runs mfile from C/FORTRAN code
 C codes (.c) . C codes generated by MATLAB compiler
 P codes (.p) . converted mfiles to hide source for security
Only script, function, and matfiles will be discussed.
Script mfile
If you have a group of commands that are expected to be executed repeatedly, it is convenient to save them in a file so that you can just refer to the file name wherever you need to use it. Here is how you can create a file mytrig.m using the MATLAB editor.
>> edit mytrig.m % invoke MATLAB editor; enter following commands
a=sin(x); % compute sine x (radians)
b=cos(x); % compute cosine x (radians)
disp( [ 'a = ' num2str(a) ] ) % prints a and b on separate lines
disp( [ 'b = ' num2str(b) ] ) % [ ... ] constitutes a string array
Select File/Save to save it as mytrig.m.
Note that x is NOT defined in the script mfile so you can set it prior to running it. A script mfile is designed to work in the same workspace (memory space) it is invoked in. The script mytrig.m has access to x as long as it is predefined.
As an example, we will define <eMx, then run mytrig.m (as a string of commands) :
>> x=30*pi/180; % converts 30 degrees to radians
>> mytrig % x is accessible to mytrig.m; both share same workspace
a = 0.5000
b = 0.8660
Function mfiles
 A function mfile must be declared with the keyword function
 A function is encapsulated. It lives in its own workspace. All input and output variables to the function must be passed between the workspace from which the function is invoked and the function's own workspace.
As an example, use MATLAB editor to create a file that computes the average of a set of numbers:
>> edit average.m
function avg=average(x)
% function avg=average(x)
% Computes the average of x
% x (input) matrix for which an average is sought
% avg (output) the average of x
avg = sum(x)/numel(x); % the average
end
Save the above with File/Save
Recommendation: save your file with the same name as your function name.
In the above, average is the function name and usually is also the file name to avoid confusion. All quantities (arrays and scalars) to be passed into the function appear as arguments (on the right hand side) to the function while the optional output appear on the left of the equal sign.
It may be called from a script, another function, or from the command line:
>> a = average(1:3) % a = (1 + 2 + 3) / 3
a =
2
>> help average % prints contiguous lines with % in average
Script or Function mfile ?
Scripts
 Pros:
 convenient; script’s variables are in same workspace as caller’s
 Cons:
 slow; script comands loaded and interpreted each time it is used
 risks of variable name conflict inside & outside of script
Functions
 Pros:
 Scope of function's variables is confined to within function. No worry of name conflict with those outside of function.
 What comes in and goes out are tightly controlled which helps when debugging becomes necessary.
 Compiled the first time it is used; runs faster subsequent times.
 Can easily be reused in another project.
 Auto cleaning of temporary variables.
 Cons:
 I/O is highly regulated, if the function requires many predefined variables, it is cumbersome to pass them in and out of the function. A script mfile is more convenient.
Some Frequently Used Functions
>> magic(n) % creates a special n x n matrix; handy for testing
>> zeros(n,m) % creates n x m matrix of zeroes (0)
>> ones(n,m) % creates n x m matrix of ones (1)
>> rand(n,m) % creates n x m matrix of random numbers
>> repmat(a,n,m) % replicates a by n rows and m columns
>> diag(M) % extracts the diagonals of a matrix M
>> help elmat % list all elementary matrix operations (or elfun)
>> abs(x); % absolute value of x
>> exp(x); % e to the xth power
>> fix(x); % rounds x to integer towards 0
>> log10(x); % common logarithm of x in base 10
>> rem(x,y); % remainder of x/y
>> mod(x, y); % modulus after division; unsigned rem
>> sqrt(x); % square root of x
>> sin(x); % sine of x; x in radians
>> acoth(x) % inversion hyperbolic cotangent of x
MATLAB Graphics
 Line plot
 Bar graph
 Surface plot
 Contour plot
 MATLAB tutorial on 2D, 3D visualization tools as well as other graphics packages available in our tutorial series.
Line Plot
>> t = 0:pi/100:2*pi;
>> y = sin(t);
>> plot(t,y)
Line Plot  continues
>> xlabel('t');
>> ylabel('sin(t)');
>> title('The plot of t vs sin(t)');
Line Plot  continues
>> y2 = sin(t0.25);
>> y3 = sin(t+0.25);
>> plot(t,y,t,y2,t,y3) % make 2D line plot of 3 curves
>> legend('sin(t)','sin(t0.25)','sin(t+0.25',1)
Customizing Graphical Effects
Generally, MATLAB's default graphical settings are adequate which makes plotting fairly effortless. For more customized effects, use the get and set commands to change the behavior of specific rendering properties.
>> hp1 = plot(1:5) % returns the handle of this line plot
>> get(hp1) % to view line plot's properties and their values
>> set(hp1, 'lineWidth') % show possible values for lineWidth
>> set(hp1, 'lineWidth', 2) % change line width of plot to 2
>> gcf % returns current figure handle
>> gca % returns current axes handle
>> get(gcf) % gets current figure's property settings
>> set(gcf, 'Name', 'My First Plot') % Figure 1 => Figure 1: My First Plot
>> get(gca) % gets the current axes. property settings
>> figure(1) % create/switch to Figure 1 or pop Figure 1 to the front
>> clf % clears current figure
>> close % close current figure; "close 3" closes Figure 3
>> close all % close all figures
2D Bar Graph
>> x = magic(3); % generate data for bar graph
>> bar(x) % create bar chart
>> grid % add grid for clarity
Save a Plot with print
>> x = magic(3); % generate data for bar graph
>> bar(x) % create bar chart
>> grid % add grid
 To add a legend, either use the legend command or use the insert command in the Menu Bar on the figure. Many other actions are available in Tools.
 It is convenient to use the Menu Bar to change a figure's properties interactively. However, the set command is handy for noninteractive changes, as in an mfile.
 Similarly, save a graph via the Menu Bar's File/'Save as' or
>> print djpeg 'mybar' % file mybar.jpg saved in current dir
Use MATLAB Command or Function ?
Many MATLAB utilities are available in both command and function forms.
For this example, both forms produce the same effect:
>> print .djpeg 'mybar' % print as a command >> print('djpeg', 'mybar') % print as a function
For this example, the command form yields an unintentional outcome:
>> myfile = 'mybar'; % myfile is defined as a string >> print .djpeg myfile % as a command, myfile is treated as text >> print('djpeg', myfile) % as a function, myfile is treated as a variable
Other frequently used utilities that are available in both forms are save
and load
Surface Plot
>> Z = peaks; % generate data for plot
>> surf(Z) % surface plot of Z
Try these commands also:
>> shading flat
>> shading interp
>> shading faceted
>> grid off
>> axis off
>> colorbar
>> colormap('winter')
>> colormap('jet')
Contour Plots
>> Z = peaks;
>> contour(Z, 20) % contour plot of Z with 20 contours
>> contourf(Z, 20); % with color fill
>> colormap('hot') % map option
>> colorbar % make color bar
Integration Example
% Integration with forloop
tic
m = 100; % number of increments
a = 0; % lower limit of integration
b = pi/2; % upper limit of integration
h = (b  a)/m; % increment length
integral = 0; % initialize integral
for i=1:m
x = a+(i0.5)*h; % midpoint of increment i
integral = integral + cos(x)*h;
end
toc
% Integration with vector form
tic
m = 100; % number of increments
a = 0; % lower limit of integration
b = pi/2; % upper limit of integration
h = (b  a)/m; % increment length
x = a+h/2:h:bh/2; % midpoint of m increments
integral = sum(cos(x)*h);
toc
Hands On Exercise
 Use the editor to write a program to generate the figure that describes the integration scheme we discussed. (Hint: use
plot
to plot the cosine curve. Usebar
to draw the rectangles that depict the integrated value for each increment.) Save as plotIntegral.m  Compute the integrals using 10 different increment sizes (h), for m=10, 20, 30, . . . , 100. Plot these 10 values to see how the solution converges to the analytical value of 1.
Hands On Exercise Solution
a = 0; b=pi/2; % lower and upper limits of integration
m = 8; % number of increments
h = (ba)/m; % increment size
x= a+h/2:h:bh/2; % m midpoints
bh = bar(x,cos(x),1,'c'); % make bar chart with bars in cyan
hold % all plots superimposed on same figure
x = a:h/10:b; % use more points to evaluate cosine
f = cos(x); % compute cosine at x
ph = plot(x,f,'r'); % plots x vs f, in red
% Compute integral with multiple m to study convergence
for i=1:10
n(i) = 10+(i1)*10;
integral(i) = sum(cos(x)*h);
end
figure % create a new figure
plot(n, integral)
More Hands On Exercises
 How would you generalize the script for arbitrary a & b ?
 How to add a title ?
 How about x, and ylabel ?
Where Can I Run MATLAB ?
There are a number of ways:
 Buy your own student version of MATLAB for $99.
 Check your department to see if there is a computer lab with MATLAB installed on the machines.
 With a valid BU userid, the engineering grid will let you gain access remotely.
Useful SCV Info
Please help us do better in the future by participating in a quick survey.
 SCV home page  Resource Applications
 Help System  help@katana.bu.edu, bu.servicenow.com
 Webbased tutorials (MPI, OpenMP, MATLAB, IDL, Graphics tools)
 HPC consultations by appointment  Kadin Tseng (kadin@bu.edu)