Software tutorial/Vectors and arrays

From Process Model Formulation and Solution: 3E4
Jump to navigation Jump to search

In this section we will focus on containers for your numbers: vectors and arrays. For the purposes of this section you should use this terminology:

Vector
A one-dimensional list of numbers
Array
A multi-dimensional arrangement of numbers
Matrix
A two-dimensional array

In this course we will mainly use vectors and matrices, however, arrays are extremely prevalent in process modelling.

Creating vectors

We will create these vectors:

  • a=[4.0,5,6,2,3,NaN,]
  • b=[0,0,,0] with 300 columns of zeros, one row
  • c=[1,1,,1]T with 300 rows of ones in a single column
  • d=[2.6,2.6,,2.6]T with 300 entries of 2.6 in one column
  • e=[4.5,4.6,4.7,,10.5, equi-spaced entries
  • f= 26 equi-spaced entries starting from 3.0, going down -4.0
MATLAB Python
a = [4, 5, 6, -2, 3, NaN, inf];
b = zeros(1, 300);
c = ones(300, 1);
d = ones(300, 1) .* 2.6;
e = 4.5:0.1:10.5;
f = linspace(3.0, -4.0, 26);

>> size(a)
ans =
     1     7
>> size(c)
ans =
   300     1
>> size(f)
ans =
     1    26

In MATLAB, everything is an array, even a scalar is just a 1×1 array, and vectors are either a 1×n or n×1 array.

import numpy as np
a = np.array([4, 5, 6, -2, 3, np.nan, np.inf])
b = np.zeros((1, 300))   # note the extra brackets!
c = np.ones((300, 1))
d = np.ones((300, 1)) * 2.6
e = np.arange(4.5, 10.5001, 0.1);  # type help(np.arange) to understand why
f = np.linspace(3.0, -4.0, 26)

>>> a.shape
(7,)
>>> c.shape
(300, 1)
>>> f.shape
(26,)

The NumPy library in Python supports two different data containers: arrays and matrices. We will not use NumPy matrices in this course, because they cannot deal with multiple dimensions (e.g. 3 dimensional arrays). And even though we will probably not use multi-dimensional arrays in this course, it is not worth learning about NumPy matrices, because they are fairly limited. So we will focus on NumPy arrays, which while a bit harder to get used to, are much more powerful than NumPy matrices. A NumPy array is roughly equivalent to a MATLAB array.

One difference though with MATLAB, is that a Numpy array with one dimension, in other words a vector, has a shape property of (n,): indicating the vector has n-elements. It is not like MATLAB where one of the dimensions is a 1 (one).

If you require the vector to be either a row vector or a column vector, then you must do so explicitly:

general_vector = np.zeros(300).shape
(300,)
row_vector = np.zeros((300, 1)).shape
(300, 1)
column_vector =  np.zeros((1, 300)).shape
(1, 300)
Unlike MATLAB