0% found this document useful (0 votes)
9 views

Matlab Beginner - V2

Uploaded by

Mengyao Zheng
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Matlab Beginner - V2

Uploaded by

Mengyao Zheng
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Introduction to MATLAB

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

• Once MATLAB is running the GUI (Graphical User


Interface) will appear
Command Window
– Main window
in MATLAB
– Commands
entered here

>> 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

• Variable ‘x’ automatically allocated


– MATLAB does not require declaration of variables
– Nice, but can get you in trouble so be careful
Interactive Commands
• Variable ‘ans’ will take value
of result of command if no
equal sign specified
• Holds most recent result only
• Semicolon at end of line will
suppress output.
• clc  Clears the command
window
• clear  Clears the workspace
Interactive Commands
• Format of output
– Defaults to 4 decimal places
– Can change using format statement
– format long changes output to 15 decimal places
Variables
• MATLAB is case sensitive
• Variable names must start
with a letter
– You’ll get an error if this doesn’t
happen
– After that, can be any
combination of letters, numbers
and underscores
• No special characters though
Variables
• Don’t name your variables the same as
functions
– min, max, sqrt, cos, sin, tan, mean, median, etc
– Funny things happen when you do this
• MATLAB reserved words don’t work either
– eps, nargin, end, pi, date, etc
Data type
• Variable types
– Numeric
– Logical
– Character and string
– Cell and Structure
– Function handle
Operators
• Scalar arithmetic operations
Operation MATLAB form
– Exponentiation: ^ ab a^b
– Multiplication: * ab a*b
– Right Division: / a / b = a/b a/b
– Left Division: \ a \ b = b/a a\b
– Addition: + a+b a+b
– Subtraction: - a–b a-b
• MATLAB will ignore white space between
variables and operators
Logical Operators

Logical operators && and || are short-circuit operators


Arrays
• MATLAB is adept at handling arrays
– Optimized for vector/matrix operations
– This allows for a reduction of code in some cases
• Array types: Numeric, character, logical, cell,
structure, function handle
– Numeric types: single, double, int8, int16, int32,
uint8, uint16, uint32
Numeric Arrays
• One dimensional arrays, called vectors
– Can create row or column vectors
– Row vector
• A few ways to create a row vector

• 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:

• Size = rows by columns


– [r c] = size(array_name) if array_name is a matrix
– size will work for n-dimension arrays and output
size of each dimension into a row vector
Numeric Arrays
• Array addressing
– Vector: foo
• foo(:) gives all row or column elements
• foo(1:5) gives the first five row or column elements
• foo(2) gives the second element
– Matrix: bar
• bar(1,3) gives the first row, third column element
• Bar(:,2) gives all elements in the second column
• Bar(1,:) gives all elements in the first row
• Bar(3:4,1:3) gives all elements in the third and fourth rows
that are in the first through third columns bar(2,1)=3

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

use “.” before the


symbol
i.e. foo.*bar
or foo./bar
or foo.^3
Numeric Arrays
• Matrix operations
– Matrix operations are the same symbols as
standard scalar operations
– Apply when multiplying or dividing matrices
Built-in MATLAB Functions
• result = function_name( input );
– abs, sign
– log, log10, log2
– exp
– sqrt
– sin, cos, tan
– asin, acos, atan
– max, min
– round, floor, ceil, fix
– mod, rem
• help elfun  help for elementary math functions
Numeric Arrays
MATLAB can create several special matrices
• zeros(n) >> a = zeros(2);
• zeros(n,m) >> b = zeros(2, 3);
• zeros(size(arr)) >> c = [1, 2; 3, 4];
• ones(n) >> d = zeros(size(c));
• ones(n,m)
• ones(size(arr))
• eye(n)
• eye(n,m)

• 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

• First line contains function keyword, output


arguments, function name and input arguments
Functions

• Comment section appears when issuing


command help rank
Functions

• Actual function code follows


– r is the return variable so that needs to be set
somewhere in the function
• rank is an example of a primary function
Functions
• Another type of function you may use is the
anonymous function
• Can be defined in a script M-file or at the
command line
– Does not need its own function M-file
• f = @(arglist)expression
• Example:
Functions
• Can create private functions, nest functions
within functions, overloaded functions
• Global variables are also available
– global var_name
– This will declare var_name as a global variable
Program Flow Control
The “if” construct is a simple, yet very useful function in
coding.

Problem: Identify if a number is below 25 or between 25


and 75 or above 75.

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

Example: count from 1 to a varying number num, and record the


counted numbers in an array.

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.

Problem: We want to find the sum of numbers 0 to 50. So we want


to find 0 + 1 + 2 + 3 + … + 49 + 50.

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

– Use vectorized version instead


Vectorizing Code
• Another way to vectorize your code is to take
advantage of built-in MATLAB functions
– Essentially all MATLAB functions can work on
arrays of any dimension
– Functions that work with manipulating arrays are
much faster than doing things in loops
Vectorizing Code
• Vectorizing code takes practice
• It is quite different from programming in C or
FORTRAN
• Getting an algorithm to work first before
vectorizing it seems to work for me
Performance Tips
• In general, use vector version of algorithm if
possible
• Use built-in functions when searching arrays,
manipulating their size and shape
• Function files execute slightly faster than
script M-files
– You can make any script M-file into a function M-
file by adding the function keyword as a wrapper

You might also like