Professional Documents
Culture Documents
Variables
Variable names:
Must start with a letter.
May contain only letters, digits, and the underscore _.
MATLAB is case sensitive, for example one & ONE are different
variables.
MATLAB only recognizes the first 31 characters in a variable name.
Assignment statement:
Variable = number; >> t=1234
Variable = expression; >>t=a+b
Special variables:
ans: default variable name for the result.
pi: = 3.1415926
eps: = 2.2204e-016, smallest value by which two numbers can differ
inf: , infinity
NAN or nan: not-a-number
yields: a = 16.6000
The answer will not be displayed
when a semicolon is put at the end of
an expression, for example type
>>a = 12+2.3*2;
for
addition
for
subtraction
for
multiplication
for
power
for
transpose
for
left division
for
right division
>>v = [1 3 5 sqrt(49)];
creates a 1x4 vector with elements 1,
3, 5 and 7.
Note that commas could have been
used in place of spaces to separate
the elements ([1,3,5,sqrt(49)]).
Additional elements can be added to
the vector:
>>v(5) = 8;
yields the vector v = [1 3 5 7 8].
Previously defined vectors can be
used to define a new vector.
For example, with v defined above
>>a = [9 10];
>>b = [v a];
creates the vector b = [1 3 5 7 8 9
10].
brackets (e.g. [27 36 41]): Creates vectors.
colon operator (e.g. [0:5:30]): Creates linearly
spaced vectors.
linspace (e.g. linspace(0,100,21)): Creates linearly
spaced vectors.
length (e.g. length([0:5:30])): Finds the length of a
vector.
zeros (e.g. zeros(1,5)): Creates vectors filled with
zeroes.
ones (e.g. ones(1,5): Creates vectors filled with
ones.
sum (e.g. sum([5 3 6 2])): Sums up the contents of
a vector.
x = [1:3:10]
Set a variable y to be the length of x.
y = length(x)
Set variable y to be the 1st element of x.
y = x(1)
Set variable y to be the 1st, 2nd, and 3rd elements
of x.
y = x([1,2,3]) OR y = x(1:3)
Set variable y to be the 3rd through the last
element of x - and do so such that your solution
works no matter how long x is.
y = x(3:end)
Set variable y to be the next-to-last and last
element of x - and do so such that your solution
works no matter how long x is.
y = x([end-1,end])
Change the 2nd element of x to be 3.
x(2) = 3
Change the 2nd element of x to be 102 and the 4th
element of x be 205.
Creating Matrices
A = [ 100 0 99 ; 7 -1 -25 ]
A=
100
99
-1
-25
The : operator
x = 1 : 7 or x = [ 1 : 7 ] creates the same vector as the command x = [ 1 2 3 4 5 6
7]
y = 0 : 3 : 12
is the same as
y = [ 0 3 6 9 12 ]
y = 0 : 3 : 11
is the same as
y=[0369]
z = 15 : -4 : 3 is the same as
z = [ 15 11 7 3 ]
w = 0 : 0.01 : 2 is the same as
w = [ 0 0.01 0.02 ... 1.99 2.00 ]
Z =[ 1
6]
transZ = Z
transZ =
1
det:
Matrix determinant
2.0000
4.0000