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