Variables and Basic Operators

In [1]:
x = 2
x =  2
In [2]:
x = 2; % x is not printed out
In [3]:
x = (2^3 + 4) / (5 * 3) - 2e10^(-10)
x =  0.80000
In [4]:
x = sin(0.0)
x = 0
In [5]:
abs(-2.5) % there's an in-built function for almost everything standard
ans =  2.5000
In [6]:
x = 1 + 1i % complex variables
x =  1 + 1i
In [7]:
abs(x) % the magnitude of a complex number
ans =  1.4142

Vectors and Matrices

In [8]:
v = [1, 2, 3, 4] % row vector
v =

   1   2   3   4

In [9]:
v = 1:4 % defining ranges
v =

   1   2   3   4

In [10]:
v = 1:0.5:4 % defining non-integer ranges
v =

    1.0000    1.5000    2.0000    2.5000    3.0000    3.5000    4.0000

In [11]:
v = linspace(1, 4, 7) % (start, stop, nb of points)
v =

   1.0000   1.5000   2.0000   2.5000   3.0000   3.5000   4.0000

In [12]:
v' % transpose the row vector
ans =

   1.0000
   1.5000
   2.0000
   2.5000
   3.0000
   3.5000
   4.0000

In [13]:
v1 = 1:5; % row vector
v2 = -5:-1; % row vector
v3 = [v1; v2]'
v3 = [v1' v2']
v3 =

   1  -5
   2  -4
   3  -3
   4  -2
   5  -1

v3 =

   1  -5
   2  -4
   3  -3
   4  -2
   5  -1

In [14]:
v3 = [v1' v2] % pay attention to dimensions
error: horizontal dimensions mismatch (5x1 vs 1x5)
In [15]:
% indexing a vector
v = [2, 3, 5, 7, 11];
v(2)
v(1:3)
v([1, 3, 5])
v(v <= 7)
ans =  3
ans =

   2   3   5

ans =

    2    5   11

ans =

   2   3   5   7