Characters and arithmetic operators
Character Description
+ Addition
- Subtraction
* Multiplication (Scalar and array)
/ Division
^ Exponential
: Creates vectors with equally spaced elements, represents rang of elements in arrays
= Assignment operator
() Parentheses; enclose input arguments in functions and subscripts of arrays
[] Brackets; forms arrays, enclose output arguments in functions
, Separates array subscripts and function arguments; separates commands in the same
line
; Suppresses display; ends row in array
‘ Single quote; matrix transpose; creates string
… Ellipsis; continuation of line
% Percent; denotes a comment, specifies output format
.* Element-by-element multiplication of arrays
./ Element-by-element division
.^ Element-by-element exponentiation
Display formats in Command window
Command (format ____ ) Description
compact Eliminates empty lines
loose Adds empty lines
short Fixed point with 4 decimal digits
long Fixed point with 15 decimal digits
short e Scientific notation with 4 decimal digits
long e Scientific notation with 15 decimal digits
bank 2 decimal digits
long g Best of 15 digit fixed/floating point
short g Best of 5 digit fixed/floating point
rat Express values from decimal to fractions
Mathematics function and rounding
Function Description
sqrt Square root
exp ex
abs Absolute value (eg. |x|)
factorial Factorial function
log ln
log10 log base 10
sin sine (in radians)
sind sine (in degrees)
asin inverse sine (in radians)
asind inverse sine (in degrees)
sinh hyperbolic sine
round Round to the nearest integer
fix Round towards zero [eg. fix(-4.34)=-4]
ceil Round towards positive infinity [eg. ceil(-4.34)=-4]
floor Round towards negative infinity [eg. floor(-4.34)=-5]
rem Returns the remainder after x is divided by y
Managing compounds
Command Description
clc Clears the command window
clear Remove all variables from memory
clear x y z Removes variables x y z from the memory
close Closes the active Figure Window
cd Changes current directory
global Declares global variables
who Displays variables currently in the memory
fclose Closes a file
fopen Opens a file
Predefined variables
Variable Description
pi 𝜋
eps Smallest difference between 2 numbers
inf or Inf Infinity
i √−1
ans Value of last expression
NaN or nan Not a number. Used to express mathematically undefined values
Creating arrays
Function Description
diag Creates a diagonal matrix from a vector.
Creates a vector from the diagonal of a matrix.
eye Creates a unit matrix (specify rows and columns if needed)
[eg. eye (1,4) = 1 0 0 0]
eye(4) = (4 rows and 4 columns)
linspace (f, l, n) Creates equally spaced vector.
f = first number, l = last number, n= number of terms
ones (r, c) Creates array with ones
zeros(r, c) Creates array with zeros
length Number of elements in the vector
size Number of rows and columns in a matrix/vector
reshape(A, m, n) Rearrange matrix (change number of rows and columns)
rand (N)/(M,N) Generate random numbers (0-1) in NxN or MxN matrix
randi (imax,N)/(imax,M,N) Generate random integers (1-imax) in NxN or MxN matrix
randn (N)/(M,N) Generate random numbers (mean 0, SD 1) in NxN or MxN matrix
A(: , n ) All rows of column n
A(m , : ) All columns of row m
A( : , m:n) All rows of columns m to n
A(m:n, : ) All columns of rows m to n
A(m:n , p:q) Columns of p to q of rows m to n
Array functions
Function Description
dot (A,B) Dot product; computes inner product of 2 vectors. (a and b → MUST same size)
det (A) Calculate the determinant of matrix A
inv Inverse of square matrix
max Maximum value
min Minimum value
median Median value
sum(v) sum
sort(v) elements sorted into ascending order (by column first)
std standard deviation
cross(v,w) cross product, (v and w → must have 3 elements)
Input to a script file
- variable_name=input(‘prompt’)
- prompt → text that input command displays in command window
- put a (1) space or (2) a colon and a space at the end of prompt → separated from the prompt
Input to a script file (string)
- method 1:
name = input (‘Your name: ‘)
- method 2:
variable_name = input(‘prompt’, ‘s’)
name = input(‘Your name: ‘, ‘s’) ➔ ‘s’: specify input is a string
fprintf to save output to file
Input and output
Command Description
disp Displays output
fprintf Displays/saves output (print column by column)
Display Character
Single quotation mark ‘‘
Percent %%
New line \n
Horizontal tab \t
Conversion specifier Format
%x.yf Fixed point
x: min. number of characters to display
y: number of decimal points to display
%e Scientific
%d Integers
%s String
input Prompts for user input
Retrieves variables to the workspace
load
save Saves variables in the workspace
xlsread Imports data from Excel
2D plot
Marker type Specifier Line color Specifier
Plus sign + Red r
Circle O Green g
Asterisk * Blue b
Point . Cyan C
Cross x Magenta m
Triangle (point up) ^ Yellow y
Triangle (point down) v Black k
Triangle (point left) <
Triangle (point right) > Line style Specifier
Square s Solid (default) -
Diamond d Dashed --
Five pointed star p Dotted :
Six-pointed star h Dash-dot -.
fplot
Plotting more than 1 set of data
- Method 1
• plot (x,y,u,v,t,h)
• plot y vs x, v vs u, h vs t
• vectors of each pair must be same size
• can use line specifiers by putting in triplets
plot (x,y,’-b’,u,v,’—r’, t,h,’g :’)
- Method 2
• Draw the first graph with plot
• Issue the command hold on
• Call plot for each of the remaining graphs
• Issue the command hold off
- Method 3
• Use line command adds additional graphs to an existing plot
line (x,y,’PropertyName’,’PropertyValue’)
• Example: plot the function y=3x3-26x+6 for −2 ≤ 𝑥 ≤ 4 together with its first and second
derivatives
Plot
Command Description
hold off Ends hold on
hold on Keeps current graph open
semilogx (x,y) Creates a plot with log scale on the x axis
semiology (x,y) Creates a plot with log scale on the y axis
loglog(x,y) Creates a plot with log scale on the both axes
xlabel Label below horizontal axis
ylabel Label left of vertical axis
title Title above plot
text (x,y,’Some text’) Text in figure with first character at (x,y)
gtext(‘some text’) Figure windows open → user clicks on graph where test is to be placed
legend(‘text 1’,’text 2’) Writes legend for 2 lines in the same order they were plotted
subplot (m,n,p) Divide figure window into m rows and n columns of subplots
Subplots numbered from left to right and top to bottom
p in subplot command refers to this numbering
grid on adds grid lines to plot
grid off removes grid lines from plot
Relational and logical operators
*Arithmetic operations (divide → multiply → add → subtract) → relational operators
Character Description
< Less than
> Greater than
<= Less than or equal
>= Greater than or equal
== Equal
~= Not equal
&/&& Logical AND
| Logical OR
~ Logical NOT
XOR Exclusive OR → only 1 true
True 1
False 0
Operator Name Description
& / && AND Both operator true.
If both are true → result: true (1).
It 1 true → result: false (0).
| OR Either 1 true.
If either one or both true → result: true (1)
Otherwise, result false (0)
~ NOT Operand is false → result: true (1)
Operand is true → result: false (0)
Command Description
if Conditionally execute commands
elseif Conditionally execute commands
else Conditionally execute commands
switch Switches among several cases based on expression (very specific input –
yes/no/maybe) NO RELATIONAL OPERATORS
case Conditionally execute commands
otherwise Conditionally execute commands (doesn’t make all the values in case stated)
for Repeats execution of a group of commands (specified loops; when you know
how many times it will run)
end Terminates conditional statements and loops
while Repeats execution of a group of commands (runs when user give the correct
command/answer)
strcmp(‘one’,’two’) Compare ‘one’ and ‘two’ → different: 0
‘one’ and ‘one’ → same: 1
(2 must be the same for while loop to end)
break Terminates execution of a loop
continue Terminates a pass in a loop
for-end loops
• To keep values without overlapping → introduce new variables (in matrix) and link it to
equation
3D line plots Surface mesh plot
- Command: plot3 (x, y, z) - Command: mesh, meshgrid
- Steps to plot: - Steps:
1. Type your 3 different vectors: X, Y and Z 1. Type x and y vectors
2. Command: plot3(x,y,z); grid on; 2. Command: [X Y] = meshgrid(“vector 1”,
3. Label axes and title “vector 2”) → create the grid of points
3. Define Z variable = function
4. Command: mesh(X,Y,Z)
5. Label axes and title
Strings
- Typing characters into the calling file
- Create by typing characters within single quotes (‘)
- Each line must have same number of columns (characters)
- Eg. names=[‘Jane’;’Jan’]
➔ 1 string 4 character, the other string 3 character → matlab prom “error”
➔ Solution → names=[‘Jane’; ‘Jan ‘] → add a spacing
Function file
- File name → same as name of function
Inverse matrix