Python example: matrices.py

This example shows how to create, manipulate, and print MRPT matrix classes in Python, as well as converting from/to numpy matrices.

 1#!/usr/bin/env python3
 2
 3# ---------------------------------------------------------------------
 4# Install python3-pymrpt, ros-$ROS_DISTRO-python-mrpt,
 5# ros-$ROS_DISTRO-mrpt2, or test with a local build with:
 6# export PYTHONPATH=$HOME/code/mrpt/build-Release/:$PYTHONPATH
 7# ---------------------------------------------------------------------
 8
 9# More matrix classes available in the module mrpt.math.
10# See: https://mrpt.github.io/pymrpt-docs/mrpt.pymrpt.mrpt.math.html
11
12from mrpt.pymrpt import mrpt
13import numpy as np
14
15# Create a numpy matrix from a list:
16m1_np = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
17
18print('m1_np   :\n' + str(m1_np))
19print()
20
21# Create an MRPT matrix from a list:
22m1_mrpt = mrpt.math.CMatrixDynamic_double_t(
23    [[11, 12, 13], [14, 15, 16], [17, 18, 19]])
24
25print('m1_mrpt :\n' + str(m1_mrpt))
26print('m1_mrpt.size() :' + str(m1_mrpt.size()))
27print()
28
29# Convert an MRPT matrix to numpy via an intermediary list:
30m2_mrpt = mrpt.math.CMatrixDynamic_double_t.Identity(3)
31m2_data = m2_mrpt.to_list()
32print('m2_data: {}'.format(m2_data))
33m2_np = np.array(m2_data)
34print('m2_np:\n{}'.format(m2_np))
35print()
36
37# Read/write access an MRPT matrix (0-based indices)
38m2_mrpt[0, 2] = 99.0  # modify the entry (0,2)
39print('m2 modified:\n{}'.format(m2_mrpt))
40m2_mrpt[0, 2] = 99.0  # modify the entry (0,2)
41print('m2[1,1]={}'.format(m2_mrpt[1, 1]))
42print()
43
44# Convert a numpy matrix to MRPT:
45m3_np = np.array([[1, 2], [3, 4]])
46m3_mrpt = mrpt.math.CMatrixDynamic_double_t(m3_np.tolist())
47print('m3_np:\n{}'.format(m3_np))
48print('m3_mrpt:\n{}'.format(m3_mrpt))

Output:

 1m1_np   :
 2[[1 2 3]
 3 [4 5 6]
 4 [7 8 9]]
 5
 6m1_mrpt :
 711 12 13
 814 15 16
 917 18 19
10m1_mrpt.size() :(3, 3)
11
12m2_data: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
13m2_np:
14[[1. 0. 0.]
15 [0. 1. 0.]
16 [0. 0. 1.]]
17
18m2 modified:
19 1  0 99
20 0  1  0
21 0  0  1
22m2[1,1]=1.0
23
24m3_np:
25[[1 2]
26 [3 4]]
27m3_mrpt:
281 2
293 4