Iwate Prefectural University Advent Calendar Day 17! Thank you for your hard work, Jack (@kazuhikoyamashita). My recent boom is Python. This time, I will try matrix operation using numpy.
NumPy is an extension module for performing numerical calculations. Please see the link below for details. http://www.numpy.org/
You need the pip command to install numpy. To install the pip command, use easy_install. Please enter the following command.
% easy_install pip
To install numpy, run the following command. The version of numpy installed this time is 1.10.2.
% pip install numpy
Collecting numpy
Downloading numpy-1.10.2-cp35-cp35m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (3.7MB)
100% |████████████████████████████████| 3.7MB 133kB/s
Installing collected packages: numpy
Successfully installed numpy-1.10.2
Prepare the matrices m1 and m2, and find the sum-difference product quotient and the inverse matrix of m1. The program is as follows.
# -*- coding: utf-8 -*-
import numpy as np
from numpy import linalg as la
m1 = np.matrix('1 2; 3 4')
m2 = np.matrix('5 6; 7 8')
#sum
print("####sum")
print(m1 + m2)
#difference
print("####difference")
print(m1 - m2)
#Product of elements
print("####Product of elements")
print(m1 * m2)
#Merchant between elements
print("####Merchant between elements")
print(m1 / m2)
#Inverse matrix of m1
print("####Inverse matrix of m1")
print(la.inv(m1))
The output result is as follows. It's convenient because the inverse matrix can be calculated easily.
% python sample.py
####sum
[[ 6 8]
[10 12]]
####difference
[[-4 -4]
[-4 -4]]
####Product of elements
[[19 22]
[43 50]]
####Merchant between elements
[[ 0.2 0.33333333]
[ 0.42857143 0.5 ]]
####Inverse matrix of m1
[[-2. 1. ]
[ 1.5 -0.5]]
that's all!
Recommended Posts