Post

Numpy & Scipy - 1.1 Notation of Matrix and Vector, Matrix Input and Output

Numpy & Scipy - 1.1 Notation of Matrix and Vector, Matrix Input and Output
Visitors


Characteristics of Numpy

  • A library for mathematical and scientific computing. It processes or computes matrices and arrays. Can generate random numbers via random.rand.



Creating a Matrix

1
2
3
4
5
6
import numpy as np # Load numpy package and use as name 'np'
a = np.array([[1,2,3],[4,5,6],[7,8,9]], dtype=np.float64) # Create 2D matrix
b = np.array([1,2,3]) # Create 1D matrix
    
print(a)
print(b)
1
2
3
4
5
[[ 1.   2.5  3. ]
 [-1.  -2.  -1.5]
[ 4.   5.5  6. ]]

[7 5 3]



shape method

  • Returns an $n imes n$ matrix as a tuple of (rows, columns).
1
2
print(a.shape) # Returns as tuple
print(b.shape) # Returns (3,). Consider it as a 1 Dimensional vector.
1
2
(3, 3)
(3,)



complex matrix

1
2
3
4
5
c = np.array([[1 - 2j , 3 + 1j, 1], [1+2j, 2-1j, 7]]) ## A number must precede j.
d = np.array([1+8j, -2j])

print(c)
print(d)
1
2
3
4
[[1.-2.j 3.+1.j 1.+0.j]
[1.+2.j 2.-1.j 7.+0.j]]

[ 1.+8.j -0.-2.j]



Data Type : dtype

  • Usually in Numpy, np.float64 is used for real parts and np.complex128 for imaginary parts.

  • Assigning an imaginary number to a real matrix a causes an error.

1
a[1,1] = 0 + 2j
1
TypeError: can't convert complex to float


  • Therefore, specify dtype explicitly when creating an array.
  • If created as a complex type, both real and imaginary numbers can be used.
1
2
a = np.array([[1, 2.5, 3], [-1, -2, -1.5], [4, 5.5, 6]], dtype=np.float64) ## dtype was omitted as default parameter
a = np.array([[1, 2.5, 3], [-1, -2, -1.5], [4, 5.5, 6]], dtype=np.complex128) ## If set to complex type initially, both real/imaginary usable


1
2
3
4
5
# Explicit type casting
a.astype(dtype=np.complex128)

# Implicit type casting
a = a + b # a:complex, b:float -> a:complex



Reading Files (.txt)

# Content of "Save/input1.txt"
1.0 2.5 3.0
-1.0 -2.0 -1.5
4.0 5.0 6.0

# "Save/input2.txt"
# complex expressions are handled within parentheses.
(1-2j) (3+j) (1) 
(1+2j) (2-j) 7


1
2
3
4
5
6
7
8
9
a = np.genfromtxt("Save/input1.txt", delimiter=" ", dtype=np.float64) # path, delimiter(space, "," ...), data type

print(a)
print(a.shape)

b = np.genfromtxt("Save/input2.txt", delimeter=" ", dtype=np.complex128)

print(b)
print(b.shape)
1
2
3
4
5
6
7
8
9
10
11
[[ 1.   2.5  3. ]
[-1.  -2.  -1.5]
[ 4.   5.   6. ]]

(3, 3)


[[1.-2.j 3.+1.j 1.+0.j]
[1.+2.j 2.-1.j 7.+0.j]]

(2, 3)



Saving Files (.txt)

  • floating format

    123.4567 => “%0.4f”

  • scientific format

    1.23e2 => “%0.2e”


1
2
3
4
5
6
7
d = np.genfromtxt("Save/input2.txt", delimiter=" ", dtype=np.complex128)

np.savetxt("Save/output.txt", d , fmt="%0.4e", delimiter="," ) # Order: path, matrix to save, format, delimiter

d = np.genfromtxt("Save/output.txt" , delimiter=",", dtype=np.complex128)

print(d)


1
2
[[1.-2.j 3.+1.j 1.+0.j]
[1.+2.j 2.-1.j 7.+0.j]]
This post is licensed under CC BY 4.0 by the author.