You are on page 1of 29

Getting Ready

• This course is a 2 hour condensed version of


Matlab Fundamentals as taught by the
Mathworks over a period of 1 day.

• Please ask questions during the class!


• You are expected to type in the examples and
see what happens (they may or may not be
correct and the only way you will know is to
find out.)
• Please contact me with any questions after the
class.
1
MATLAB Naming Conventions

• MATLAB was written to run on a unix


system
– Capitalization counts
– Spaces are command delimiters unless
enclosed in single quotes.
– Support for a large set of Unix commands
without having to exit environment.
– Variable names cannot start with a number.
– Strings are delimited with single quote (‘)
– Variables should be descriptive (don’t use
abbreviations) 2
Opening up the Application
• Create the following directory in the MATLAB work
area.
C:\Users\Ehamke\Documents\MATLAB\Training

• MATLAB has a directory structure that it uses for


managing its toolboxes (object libraries). They have
reserved the “…\Documents\MATLAB” directory for
your work. (You can change this as you see fit but
please be consistent and do not use any of the other
directories.)

• Launch the MATLAB application.

• After launching MATLAB you should get the following


screen.
3
Matlab Desktop Display
Current Directory

Variable
Explorer

Command Window

Command
History

4
Undocking a Window
Click ‘Undock’ button on frame to undock the window
Current Directory is
undocked in its
own window

5
Docking a Window

Click ‘Dock’
button on frame
to dock the
window.

6
Configuring the Matlab Desktop

7
Main Screen (Command Prompt)

Command prompt.
(Note: MATLAB still supports its command
interpreter language and you still can write
scripts. This region of the screen allows you to
launch the scripts, the script editor, and models.)

If you wish to get help on a command. Type “help


command name”. For example,

Try typing the following.

help help

8
Help Function

You should get a display


like this.

Please note you may have


to use your scroll bar to find
the top of the response to
the command.

9
Navigating Help Topics
• There is a help entry for each toolbox installed. The
following partial list is an example.
matlab\general - General purpose commands.
matlab\ops - Operators and special characters.
matlab\lang - Programming language constructs.
matlab\elmat - Elementary matrices and matrix manipulation.
matlab\elfun - Elementary math functions.
matlab\specfun - Specialized math functions.
matlab\matfun - Matrix functions - numerical linear algebra.
matlab\datafun - Data analysis and Fourier transforms.
matlab\polyfun - Interpolation and polynomials.
matlab\funfun - Function functions and ODE solvers.
matlab\sparfun - Sparse matrices.
matlab\scribe - Annotation and Plot Editing.

These entries can be accessed by typing help followed by


the toolbox name.
help matlab\general.
10
Navigating Help Topics (continued)

• MATLAB will display the following in the


command window.
Managing the workspace.
who - List current variables.
whos - List current variables, long form.
clear - Clear variables and functions from
memory.
pack - Consolidate workspace memory.
load - Load workspace variables from disk.
save - Save workspace variables to disk.
saveas - Save Figure or model to desired
output format.
memory - Help for memory limitations.
recycle - Set option to move deleted files to
recycle folder.
quit - Quit MATLAB session.
exit - Exit from MATLAB.

11
Anatomy of a Help Topic Entry
• Type “help quit”. The following should appear
Standard format
QUIT Quit MATLAB session.
QUIT terminates MATLAB after running the script FINISH.M,
if it exists. The workspace information will not be saved Command description
unless FINISH.M calls SAVE. If an error occurs while
executing FINISH.M, quitting is cancelled.

QUIT FORCE can be used to bypass an errant FINISH.M that


will not let you quit.

QUIT CANCEL can be used in FINISH.M to cancel quitting.


It has no effect anywhere else.

Example
Put the following lines of code in your FINISH.M file to Command usage
display a dialog that allows you to cancel quitting.

button = questdlg('Ready to quit?', ...


'Exit Dialog','Yes','No','No');
switch button
case 'Yes',
disp('Exiting MATLAB');
%Save variables to matlab.mat
save
case 'No',
quit cancel;
end

Note: When using Handle Graphics in FINISH.M make sure


to use UIWAIT, WAITFOR, or DRAWNOW so that figures are
visible.
Cross-Reference to other
See also exit.
related commands
Reference page in Help browser
doc quit
Command to bring up Reference Manual entry

12
HTML Formatted Help Topic Entry

13
Matlab ‘WHICH’ function

– Useful for determining names of built


in functions so user defined functions
and/or scripts are not identically
named
– If user defined functions and/or
scripts are identically named with a
built in functions, unpredictable
results could occur, depending on
how the path values are set.

14
Command Punctuation

– Matlab variables are case sensitive


– Matlab filenames are not case sensitive on NT platforms,
filenames are case sensitive on other platforms. Portability
issue.
– Matrix Elements are accessed via (Row, Column)
– [ ] Matrix delimiter
– , or a space starts a new column in a matrix definition
– ; starts a new row in a matrix definition
– : is a numeric sequence generator
– ; at the end of a line suprresses output in the Matlab
Command Window

15
Iteration

• Generally software design uses iteration


for
– Moving data from one structure to another.
– Repeating a set of instructions until some
condition is false.
– Creating counts

• MATLAB supports all these behaviors but


in a different way than you are used to.
(c) Eric E Hamke, Feb 2015, All Rights 16
Reserved
Colon Operator
(Initializing Sequences)

A matrix is a 2
dimensional array
C-Code Equivalent
(matrix) // The loop goes while x < 10, and x
//increases by one every loop
for ( int x = 0; x < 11; x++ ) {
// Keep in mind that the loop condition
A vector is a 1 dimensional array. // checks the conditional statement
// before it loops again. Consequently,
// when x equals 10 the loop breaks.
// x is updated before the condition is
// checked.
cout << x <<endl;
}

Note: Sequence generator has three elements, the starting index,


increment size, and ending index. The increment size index is optional
and defaults to 1. 17
Iteration (Moving Data)
• MATLAB assumes that the native data structure is an n-
dimensional matrix or array.
• Assignment operations automatically transfer data from
one array to the next without the user having to do this
explicitly.

C-Code Equivalent
float A[11];
float B[11];

// The loop goes while x < 10, and x


//increases by one every loop
for ( int i = 1; x < 11; i++ ){
A(i) = i/10 + 1;
B(i) = A(i);
cout << A(i) <<endl;
cout << B(i) <<endl;
}

(c) Eric E Hamke, Feb 2015, All Rights 18


Reserved
Iteration (Repeating Instructions)

• This usually takes the form of “do while” or “do until”. (This typically happens when a
set of calculations may need to be repeated until a set of conditions are true.)
• In MATLAB you have the while statement which repeats a set of statements an
indefinite number of times. The general form of a while statement is:
while (expr rop expr )
statements
end
• The statements are executed while the real part of the expression has all non-zero
elements. The expression is usually the result of expr rop expr where rop is {==, <, >,
<=, >=, or ~=}.
• The BREAK statement can be used to terminate the loop prematurely.
• For example (assuming A already defined):
A=[1 2 3; 4 5 6; 7 8 9];
E = 1.*A; Example of infinite loop and the use of ^c
F = E + eye(size(E));
N = 1;
while norm(E+F-E,1) > 0,
E = E + F;
F = A*F/N;
N = N + 1;
end

(c) Eric E Hamke, Feb 2015, All Rights 19


Reserved
Sequence Operations
All operators perform the same operation on every element in
the sequence
^ power
C-Code Equivalent
* multiplication float A[11];
float B[11];
/ division
// The loop goes while x < 10, and x
+ addition //increases by one every loop
for ( int i = 1; x < 11; i++ ){
- subtraction A(i) = i/10 + 1;
B(i) = A(i)*2;
cout << A(i) <<endl;
cout << B(i) <<endl;
}

20
Arithmatic Operators

• Matrix Operations • Element Operations


() parentheses .’ Real transpose
‘ complex transpose .^ power
^ power .* multiplication
* multiplication ./ division
/ division + addition
\ left division - subtraction
+ addition
- subtraction

21
Matrix Operators Example

Matrix operators perform the linear algebra


operations.

a a  a a 
a '   11 21  where, a   11 12 
a12 a22  a21 a22 
a b  a b a b a b 
ab   11 11 12 21 11 12 12 22 
a21b11  a22b21 a21b12  a22b22 
 a11 a12  b11 b12 
where, a    and b  b b 
 21 22 
a a  21 22 

 a b a b  Array operators perform


ab   11 11 12 12 
a21b21 a22b22  the operation on an
element by element
basis. 22
Solving Simultaneous Equations
Given,
 x1  x2  2 x3  2
3 x1  x2  x3  6
 x1  3 x2  4 x3  4
Solve for x

Observe that
x  A1b
where
  1 1 2  x1 
A   3  1 1  x   x2 
 1 3 4  x3 
 2
and b  6
4
23
Array Operation Example

• Given the following sample


data calculate average
volume of the cubes
lengths = 3.0, 3.1, 2.9
widths = 4.8, 5.0, 5.1
heights = 2.2, 1.9, 2.0
• Could calculate average
volumes as:
for I=1 to 3
v(I)=length(I) *
width(I) * depth (I)
vTotal = vTotal+v(I)
Using array operators is much next I
more efficient than loops since averageV=vTotal/3
Matlab is matrix based

24
Matlab Cell Arrays - Example
Voltage Current
Experiment ID Measurements Measurements

Calculated Resistances

Experimental Data

25
Matlab Structures - Example

Using the same


experimental Data from
same 3 experiments in prior
example

26
File I/O - Reading data from Excel

• Given the following Excel spreadsheet, read the data into the
Matlab workspace. (The spread sheet contains both numerical and
text data.)

27
File I/O - Reading data from delimited text files

Given the following delimited


text, read the data into the
Matlab workspace. (The text
file contains numerical data
only.)

28
File I/O - Reading data from comma delimited text
files
Given the following comma delimited text, read the data into
the Matlab workspace. (The text file contains numerical
data only.)

29

You might also like