Matlab Beginner - V2
Matlab Beginner - V2
What is MATLAB?
• MATLAB is a simple programming language
with its own extensive library of mathematical
and graphical subroutines
• Integrates computation and graphics in one
easy to use interface
• Stands for MATrix LABoratory.
• Extendable. There are many add-ons
(toolboxes) for specific requirements
Starting MATLAB
• Double click the Matlab icon
>> prompt
Current Folder Window
– Displays contents of the current
working directory
– MATLAB Search Path
• Path that MATLAB uses to search for
script and function files
• Default path contains all built in
MATLAB functions
• Can modify path through MATLAB
function or going under File>Set Path
• MATLAB will ask to modify path if
running a program from a folder not in
path
• Workspace Window
– Shows all currently defined
variables
– Array dimensions
– Min, max values
– Good debugging tool
• Command History
– Shows all past commands
– Can copy and past commands
into command window
– Double click will execute
command
MATLAB GUI
• Other windows include editor window, figure
window, variable editor, help, etc
MATLAB Help
• Ways to get help in MATLAB
– help function name
– Provides basic text
output
• Look under the help
menu on the desktop
MATLAB Help
• Product help window
– Help>product help
Interactive Commands
• Enter commands at >> prompt
• Or use “:”
o arr = 1:5
o arr = 1:2:10
Numeric Arrays
• Column vectors
– A few ways to generate column vectors too
– Semicolon between elements starts new row
– Transpose a row vector, or use return between
elements
Numeric Arrays
• Two-dimensional arrays, called a matrix in
MATLAB often
• Basic matrix creation:
Row # Column #
Numeric Arrays
• Array operations
– element by element operation
– matrix operations
– Multiplying a vector or array by a scalar is an easy
example
Numeric Arrays
• How do you multiply to arrays element-by-
element?
– Addition and subtraction are the same: +, -
– Multiplication, right and left division and
exponentiation
• length(arr)
• size(arr)
• isnan, isempty, isinf
Strings
• Strings are just character arrays
– Can be multidimensional
– However, each string is required to
be the same length to keep array
rectangular
Strings
• Useful functions
– String manipulation: sprintf, strcat, strvcat, sort,
upper, lower, strjust, strrep, strtok, deblank, etc.
– String comparisons
• Should use strcmp when comparing strings
• If you have two strings A and B, A==B will give a row
vector of results for each character
• Strcmp will compare the entire string, or a subset if you
want
M-Files
• MATLAB has the editor window for creating,
editing, debugging, running and saving m-files
• MATLAB color codes m-files for easier reading
• There is also real-time syntax checking
– Essentially spell check for code
M-files
• Example m-file
Scripts
• M-files are essentially script files where you
can place a bunch of MATLAB commands and
execute the m-file repeatedly
– Can have everything in an m-file, function calls,
variable allocation, function definitions, figure
generation and modification, etc
• Nearly everything will probably be done in an
m-file, rather than at the command prompt
Functions
• Functions are M-files that accept input and
output arguments
• The M-file needs to have the same name as
the function
• Functions create their own local workspace
– You won’t see variables used in function call in
main workspace
Functions
• Look at example function: rank
Solution:
if inp < 25
disp('less than 25')
elseif 25 <= inp && inp <= 75
disp('between 25 and 75')
else
disp('above 75')
end
Program Flow Control
switch, case, otherwise
Execute one of several groups of statementsexpand all in page
Syntax
switch switch_expression
case case_expression
statements
case case_expression
statements
...
otherwise
statements
end
Problem: We are told that we will be given an input, which can
either be 1, 2, 3 or something else. We need to make a program
that will tell us which is which.
Solution:
switch inp
case 1
disp('one')
case 2
disp('two')
case 3
disp('three')
otherwise
disp('others')
end
end
Program Flow Control
while
Repeatedly execute statements while condition is true
Syntax
while expression, statements, end
Num = 12;
array = 0;
i = 1;
while array(1,i) < num
i = i+1;
array(1,i) = array(1,i-1)+1;
end
disp(array)
Program Flow Control
“for loops” will repeat a series of statements a specific number of
times. They help us by making Matlab do all the repetitive work for
you.
Solution:
>> a = 0;
for i = 1:50 a = a + i; end
>> a
a =
1275
Basic Plotting
• plot(x,y)
– Basic MATLAB plotting command
– Creates figure window if not already created
– Autoscales each axis to fit data range
– Can add axes object properties after x,y
• figure(n)
– Will create a new figure window
– MATLAB will use current figure window by default
– Plot command will overwrite figure if called repeatedly
given same current figure window
Basic Plotting
• Create a simple
plot from the
command line
Basic Plotting
• grid command will turn on x, y-axis grid lines
• axis([xmin xmax ymin ymax])
– Command to set axis limits
– axis square will set the axis limits such that the
plot is square
– axis equal will set scale factor and tick marks to
be equal on each axis
– axis auto will return axis scaling to auto, which is
default
Basic Plotting
• xlabel(‘text’)
• ylabel(‘text’)
• title(‘text’)
– These three commands will set the xlabel, ylabel
and title of the plot for you
– The grid, axis and labeling commands all need to
be performed after the plot command
Figure Window
• All editing of figure can be done manually in
figure window
• Can insert title, axis labels, legend, change axis
scaling, tick marks and labels, etc
Figure Window
• File menu
– Save, open, close, print figure
• Can save as many different image
formats: png, jpg, eps, tif, etc.
• Edit menu
– Edit axis properties, figure
properties
• Insert menu
– Insert title, legend, axis labels
• Tools menu
– Change view of plot, add basic
Basic Plotting
• h = plot(x,y)
– h is a vector of handles to lineseries objects
– This allows you to use h to edit the appearance of the
data being plotted (i.e. line color, line style, line width)
• h = figure(n)
– h is a handle to figure n
– This allows you to modify properties of the figure
object
• Useful if you are creating many figures and want to modify
them at different points in the program
Saving Figures
• Figures can be saved in a few ways
– File -> Save or Save As
– Save button on figure toolbar or Ctrl+S
– Save As gives many options for output format
• Two functions to save figures
• saveas(h,'filename.ext') or
saveas(h,'filename','format')
– Where h is a figure handle (figure number) and
‘.ext’ or ‘format’
Vectorizing Code
• Don’t use loops everywhere
– Use them sparingly