Programming MATLAB
Paul Cotofrei
information management institute master of science in finance
2018
Outline
Variables, Constants, Keywords
Data Types
Variables and Assignment
Computerprogramsmanipulatesdata;foraneasyaccess,data (values) are stored in memory containers.
Variable-anamedmemorycontainer
Tostoreavalueinavariable:useanassignmentstatement
General form/syntax: variable = expression
Theorderisimportant
variable name on the left
the assignment operator “=” (Note: this does NOT mean
equality)
expression (known value) on the right
Example(atCommandWindowprompt):
Asemicolonsuppressestheoutput:
» price = 60.5
price =
60.5000
» price = 60.5;
»
Variable names
Names:characterstringstartingwithanupperorlowerletter and containing upper or lower letters, digits, and underscores
MATLABiscase-sensitive
Predefinedvariables(constants):
pi – π number √
iorj– −1number
Inf – ∞ number, as in 1/0
NaN–NotaNumber,asin0/0
true – logical value 1
false – logical value 0
etc..
Warning:NoMATLABerrormessagewhenredefininga predefined variable !
» pi = 2;
» true = 0;
Variable names
ans-a”bydefault”variablename,wherenospecificvariableis used to store a value
Specialkeywordsthatcannotbeusedasvariablenames:
» -5/(4.8 + 5.32)^2
ans =
-0.048821
» iskeyword
break
case
catch
classdef
continue
else
elseif
end
for
function
global
if
otherwise
parfor
persistent
return
switch
try
while
Variable Editor Windows
Expressions
variable=expression
Expressionscancontainvalues,variablesthathavealready
been created, operators, built-in functions, and parentheses
Operatorsinclude:
+
addition
−
negation, subtraction
∗
multiplication
/
division (divided by e.g. 10/5 is 2)
\
division (divided into e.g. 5\10 is 2)
ˆ
exponentiation (e.g. 5ˆ2 is 25)
Operatorprecedence: () parentheses
ˆ exponentiation
− negation
∗,/,\ all multiplication and division +,− addition and subtraction
Nestedparentheses:expressionsininnerparenthesesare evaluated first
Built-in functions
Therearemany,MANYbuilt-infunctionsinMATLAB
Relatedfunctionsaregroupedintohelptopics
Touseafunction,youcallit
Tocallafunction,giveitsnamefollowedbytheargument(s)that are passed to it in parentheses
Usually,built-infunctionscalculatevaluesandreturntheresults
Example:
The name of the function is sin
One argument, pi, is passed to the sin function
The sin function calculates the value and returns the result
1.2246e-16 (Why not 0?)
»sin(pi)
ans =
1.2246e-16
MATLAB as calculator
» ((((1 + 2)*3 + 4)*5 + 6)*7) + 8
ans =
505
» (5^3 + 6^(-2))/(1 + sin(pi/2))
ans =
62.5139
» exp(abs(-5)) + log(13)
ans =
150.9781
» round(5.2)^2 + sqrt(64)
ans =
33
» a = 2;
» b = 20;
» c = a^b
ans =
1048576
Outline
Variables, Constants, Keywords
Data Types
Basic Data Types
Everyexpressionandvariablehasanassociatedtype,orclass
Fundamentaldatatypes(classes)
Homogenous classes : Numeric, Boolean, String
Non-homogenous classes : Structures, Cell arrays
MATLABDataStructure:n-dimensionalmatrix
Scalar : 1 × 1 matrix
Vector:1×morm×1matrix
Array:k1×k2×···knmatrix
Numeric Classes
Realnumbers:single,double Integernumbers:
Used only for certain applications (e.g. image processing) Numericvariablesarestoredbydefaultasdoubleprecision
numbers
Predefinedvariables
realmin (smallest positive floating point number: 2.23e-308)
realmax (largest positive floating point number: 1.80e+308)
eps (relative precision: 2.22e-16)
intmax (largest integer number: 2147483647, i.e. 231 − 1 )
Formatting
Tochangehowthenumericvariablesaredisplayed,usethe command , where
short, long : fixed format up to with 5(or 15) decimal digits
short e, long e : floating format up with 4(or 15) decimal digits
short g, long g : the best format (fixed or floating)
Example-displayedvalueof10*piindifferentformats
» format
31.4159 31.415926535897931 3.1416e+001
31.416 3.141592653589793e+001 31.4159265358979
% format, or format short % format long
% format short e
% format short g
% format long e % format long g
Scientificorexponentialnotation:useeforexponentof10 raised to a power: e.g. 3e5 means 3 ∗ 105
» 3e5 ans =
300000
Basic input/output functions: disp, input
» x = 10;
» disp(’the value of x is:’); disp(x);
the value of x is:
10
» x = input(’enter x: ’) % numerical input enter x: 100 % 100 entered by user x=
100
» y = input(’enter string: ’, ’s’) % string input
enter string: abcd efg % string entered with no quotes y=
abcd efg
» y = input(’enter y: ’); % numerical or string input
enter y: ’abcd efg’ % string entered in quotes
» disp(y);
abcd efg
» help fprintf
Useful commands
who
List the variables in the current workspace
whos
List the variables in the current workspace, with information about size and type (class)
class(obj)
returns the name of the class for the variable/ex- pression obj
clear
Remove variables and function from the workspace memory
which
Identify and locate functions and files
what
List MATLAB files in current directory (grouped by type)
clc
Clear the Command Window
date
Generates a string containing the current date
save
Saves all of your variables
load
Loads back all of the variables which have been saved previously
input(’
Displays the prompt on the screen and waits to input whatever is desired. The optional second argument of ’s’ allows to enter a string (including spaces) without using quote marks.
type
Displays the actual MATLAB code for this com- mand
To remember …
BewareofCommonPitfalls
Confusing the order in an assignment statement (make
sure that the variable name is always on the left)
Forgetting to use parentheses to pass an argument to a
function (e.g., typing round 2.3 instead of round(2.3)) ProgrammingStyleGuidelines
Use mnemonic variable names (names that make sense; for example, interest instead of xyz)
Although variables named result and RESULT are different, avoid this as it would be confusing
Do not use names of built-in functions as variable names
Store results in named variables (rather than using ans) if
they are to be used later