Python example: matrices.py
Creates, prints and converts MRPT matrices from/to NumPy arrays.
Modules: mrpt.math
1#!/usr/bin/env python3
2"""
3Creates, prints and converts MRPT matrices from/to NumPy arrays.
4"""
5
6from mrpt.math import CMatrixDouble
7import numpy as np
8
9# Create a numpy matrix from a list:
10m1_np = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
11print('m1_np :\n' + str(m1_np))
12print()
13
14# Create an MRPT matrix from a list:
15m1_mrpt = CMatrixDouble([[11, 12, 13], [14, 15, 16], [17, 18, 19]])
16print('m1_mrpt :\n' + str(m1_mrpt))
17print('m1_mrpt shape:', np.array(m1_mrpt.as_numpy()).shape)
18print()
19
20# Convert an MRPT matrix to numpy (CMatrixDouble has as_numpy but not to_list or Identity):
21m2_mrpt = CMatrixDouble(np.eye(3).tolist()) # 3x3 identity
22m2_np = np.array(m2_mrpt.as_numpy())
23print('m2_np (identity):\n{}'.format(m2_np))
24print()
25
26# Read/write access: CMatrixDouble doesn't support __setitem__, use numpy round-trip
27m2_arr = np.array(m2_mrpt.as_numpy())
28m2_arr[0, 2] = 99.0 # modify the entry (0,2)
29m2_mrpt = CMatrixDouble(m2_arr.tolist())
30print('m2 modified:\n{}'.format(m2_mrpt))
31print('m2[1,1]={}'.format(m2_arr[1, 1])) # index via numpy array
32print()
33
34# Convert a numpy matrix to MRPT:
35m3_np = np.array([[1, 2], [3, 4]])
36m3_mrpt = CMatrixDouble(m3_np.tolist())
37print('m3_np:\n{}'.format(m3_np))
38print('m3_mrpt:\n{}'.format(m3_mrpt))
Output:
m1_np :
[[1 2 3]
[4 5 6]
[7 8 9]]
m1_mrpt :
11 12 13
14 15 16
17 18 19
m1_mrpt shape: (3, 3)
m2_np (identity):
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
m2 modified:
1 0 99
0 1 0
0 0 1
m2[1,1]=1.0
m3_np:
[[1 2]
[3 4]]
m3_mrpt:
1 2
3 4