473,729 Members | 2,234 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

native python matrix class (2D list), without inverse


# Copyright (C) 2007 Darren Lee Weber
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.

__version__ = "$Revision: 1.9 $" # $Date: 2007/06/14 00:24:57 $

class Matrix:
"""
Create and manipulate a matrix object

Matrix(data, dim)

data = list of lists (currently only 2D)
dim=(row,col) tuple of int

For example,

#data = [[0.0] * c for i in xrange(r)]
data = [[0.0,0.1],[1.0,1.1],[2.0,2.1]]
rowN =len(data)
colN =len(data[0])
m = Matrix(data)
m = Matrix(data,dim =(rowN, colN))

d1 = [[0.0, 0.1], [1.0, 1.1], [2.0, 2.1]] # 3x2 matrix
d2 = [[0.0, 0.1, 0.2], [1.0, 1.1, 1.2]] # 2x3 matrix
m1 = Matrix(d1)
m2 = Matrix(d2)
#m3 = m1 + m2 # dimension error
m3 = m1 + m2.transpose()
m3 = m1 - m2.transpose()
m3 = m1 * m2 # 3x3
m3 = m2 * m1 # 2x2

m1[2,:]
m1[:,2]
"""

def __init__(self, data=None, dim=None):
"""
create a matrix instance.

m = Matrix([data [, dim]])

<datais a 2D matrix comprised of a nested list of floats
<dimis a tuple of int values for the row and column size
(r,c)

eg:
data = [[0.0,0.1],[1.0,1.1],[2.0,2.1]]
dim = (3,2) # or (len(data),len( data[0]))
"""

if data != None:
# check data for the cell types (ensure float)?
self.data = data
r = len(data)
c = len(data[0])

# Are all the rows the same length?
rowLenCheck = sum([len(data[i]) != c for i in range(r)])
if rowLenCheck 0:
raise ValueError
else:
self.dim = (r,c)

if dim != None:
if (dim[0] == r) and (dim[1] == c):
self.dim = (r,c)
else:
# over-ride the dim input, do not reshape data!
# print a warning?
self.dim = (r,c)
else:
if dim != None:
if len(dim) == 2:
self.dim = tuple(dim)
r = dim[0]
c = dim[1]
else:
# maybe a new exception type?
arg = ("len(dim) != 2: ", dim)
raise ValueError, arg

# BEGIN ALT ----------------------------------------
# Does this give unique memory for each element?
# self.data = [[0.0] * c for i in xrange(r)]

# It seems that the initialization does not generate
# unique memory elements because all list elements
# refer to the same number object (0.0), but
# modification of any element creates a unique value,
# without changing any other values, eg:

##>>x = [[0.0] * 3 for i in xrange(2)]
##>>id(x)
# 3079625068L
# >>id(x[0][0])
# 136477300
# >>id(x[0][1])
# 136477300
# >>id(x[1][1])
# 136477300
# >>x[0][0] = 1.0
# >>x
# [[1.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
# >>>
# END ALT ----------------------------------------

# create a zero row vector, with unique memory for
each element
self.data = [[x * 0.0 for x in range(c)]]
for i in range(1,r):
self.data.appen d([x * 0.0 for x in range(c)])
else:
self.data = []
self.dim = (0,0)
#print self.__doc__

def __getitem__(sel f, i):
"""
matrix[r,c] returns values from matrix.data, eg:
data = [[0.0,0.1],[1.0,1.1],[2.0,2.1]]
m = Matrix(data)
m[2,:]
>[2.0, 2.1000000000000 001]
"""
r = i[0]
c = i[1]
#print "index: (%s, %s)" % (r,c)
#print "value: ", self.data[r][c]
return self.data[r][c]

def reshape(self, newdim=None):
'reshape a matrix object: matrix.reshape( newdim)'
print "something to implement later"
pass

def transpose(self) :
'transpose a matrix: m2 = m1.transpose()'
m = Matrix(dim=(sel f.dim[1],self.dim[0]))
for r in range(self.dim[0]):
for c in range(self.dim[1]):
m.data[c][r] = self.data[r][c]
return m

def __add__(self, q):
'''
matrix addition:
m3 = matrix1 + matrix2
m3 = matrix1 + float
m3 = matrix1 + int
'''
if isinstance(q, Matrix):
if self.dim != q.dim:
arg = ("p.dim != q.dim", self.dim, q.dim)
raise IndexError, arg
else:
# do the addition
m = Matrix(dim=self .dim)
for r in range(self.dim[0]): # rows of p and q
m.data[r] = map(lambda x, y: x + y, self.data[r],
q.data[r])
return m
elif isinstance(q, float) or isinstance(q, int):
# add a scalar value
m = Matrix(dim=self .dim)
for r in range(self.dim[0]): # rows
m.data[r] = map(lambda x: x + q, self.data[r])
return m
else:
arg = ("q is not a matrix, float or int", q)
raise TypeError, arg

def __sub__(self, q):
'''
matrix subtraction:
m3 = matrix1 - matrix2
m3 = matrix1 - float
m3 = matrix1 - int
'''
if isinstance(q, Matrix):
if self.dim != q.dim:
arg = ("p.dim != q.dim", self.dim, q.dim)
raise IndexError, arg
else:
# do the subtraction
m = Matrix(dim=self .dim)
for r in range(self.dim[0]): # rows of p and q
m.data[r] = map(lambda x, y: x - y, self.data[r],
q.data[r])
return m
elif isinstance(q, float) or isinstance(q, int):
# subtract a scalar value
m = Matrix(dim=self .dim)
for r in range(self.dim[0]): # rows
m.data[r] = map(lambda x: x - q, self.data[r])
return m
else:
arg = ("q is not a matrix, float or int", q)
raise TypeError, arg

def __mul__(self, q):
"""
multiply two matrices:
m = p * q # p.dim[1] == q.dim[0]

multiply a matrix with a scalar:
m = p * q # where q is a float or int value
"""
if isinstance(q, Matrix):
if self.dim[1] != q.dim[0]:
arg = ("p.dim[1] != q.dim[0]", self.dim[1], q.dim[0])
raise IndexError, arg
else:
# do the multiplication
m = Matrix(dim=(sel f.dim[0], q.dim[1]))
for r in range(self.dim[0]): # rows of p
for c in range(q.dim[1]): # cols of q
# get the dot product of p(r,:) with q(:,c)
pRowVec = self.data[r]
qColVec = [q.data[a][c] for a in
xrange(q.dim[0])]
m.data[r][c] = sum(map(lambda x, y: x * y,
pRowVec, qColVec))
return m
elif isinstance(q, float) or isinstance(q, int):
# subtract a scalar value
m = Matrix(dim=self .dim)
for r in range(self.dim[0]): # rows
m.data[r] = map(lambda x: x * q, self.data[r])
return m
else:
arg = ("q is not a matrix, float or int", q)
raise TypeError, arg

def __div__(self, q):
"""
Divide a matrix with a scalar, eg:
m = p / q # where q is a float or int value
This operator will not return a matrix inverse
"""
if isinstance(q, Matrix):
# let's not do matrix divide in python, leave the inverse
# to a c/c++ library
arg = ("q is a matrix: will not calculate inverse", q)
raise TypeError, arg
elif isinstance(q, float) or isinstance(q, int):
# divide a scalar value
m = Matrix(dim=self .dim)
for r in range(self.dim[0]): # rows
m.data[r] = map(lambda x: x / q, self.data[r])
return m
else:
arg = ("q is not a matrix, float or int", q)
raise TypeError, arg

def __len__(self):
return self.dim[0] * self.dim[1]

def __str__(self):
# print the matrix data
s = ""
for r in range(self.dim[0]):
for c in range(self.dim[1]):
s += "%f " % (self.data[r][c])
s += "\n"
return s

def printFormat(sel f, format):
"""
print the matrix data nicely formatted, eg:
matrix.printFor mat("%8.4f")
"""
for r in range(self.dim[0]):
for c in range(self.dim[1]):
print format % (self.data[r][c]),
print

def __repr__(self):
# return something that will recreate the object
return "Matrix(%s, %s)" % (self.data, self.dim)

#
--------------------------------------------------------------------------------
# Explore the functionality - should be unit testing

testing = 0
if testing:
d1 = [[0.0, 0.1], [1.0, 1.1], [2.0, 2.1]] # 3x2 matrix
d2 = [[0.0, 0.1, 0.2], [1.0, 1.1, 1.2]] # 2x3 matrix
m1 = Matrix(d1)
m2 = Matrix(d2)
#m3 = m1 + m2 # "dimension" error
m3 = m1 + m2.transpose()
m3 = m1 - m2.transpose()
m3 = m1 * m2 # 3x3
m3 = m2 * m1 # 2x2
m3 += 10.0
m3 -= 10.0
m3 += 10
m3 -= 10
m3 /= 10.0
m3 *= 10.0
m3 /= 10
m3 *= 10

Jun 14 '07 #1
0 2809

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
16723
by: Charulatha Kalluri | last post by:
Hi, I'm implementing a Matrix class, as part of a project. This is the interface I've designed: class Matrix( )
7
2730
by: check.checkta | last post by:
Hi, I'd like to implement a simple matrix class. I'd like to overload operator so that it returns as a vector (either the stl vector or some other Vector class of my own). The reason I want to do this is because it enables me to apply some functions of a vector to a row of of matrix, e.g., I have a function to compute the sum of vector: double my_sum(vector<double> x) {
7
14245
by: mariaczi | last post by:
Hi, I code class to storage sparse matrix row compressed and i have a problem with implements method to setVal and addVal. I will replace later this methods overloaded operator(). Please, can You help me? Thanks in advance. I write this, but it's not so good :(
8
1593
by: MVM | last post by:
I am new to VS 2003. I did programming in vb6 and vc6, but not through studio. I am having lot of confusion on how to start, where to start? I like to write a program in vc++ under vs 2003. i just need exe file that can be used in command prompt. where do i start? the program should read a file with unkown size matrix. get inverse, do some manipulations and muliplications. I see there is a class Matrix. which include file i...
14
6215
by: Paul McGuire | last post by:
I've posted a simple Matrix class on my website as a small-footprint package for doing basic calculations on matrices up to about 10x10 in size (no theoretical limit, but performance on inverse is exponential). Includes: - trace - transpose - conjugate - determinant - inverse - eigenvectors/values (for symmetric matrices)
1
2176
by: Wayne Shu | last post by:
Hi everyone: I'm looking forward to a wonderful matrix class library! Does someone like to introduce a to me? It should satisfy the following demands: 1. Open Source. 2. Efficient. 3. Support basic matrix operations: +, -, *, transpose, inverse, convolution. 4. Support multi-dimension matrix, e.g. for a 24-bit bitmap, if I
5
2802
by: =?Utf-8?B?TWFuanJlZSBHYXJn?= | last post by:
Hi, I developed a custom Matrix class derived from custom VC++ doubles Array class derived from a RealArray which is defined as: typedef CArray<double,doubleRealArray; Now I need to convert this custom Matrix class to standard doubles Matrix (VC++) as I am passing it to some function that understands only the standard class.
2
2665
by: rijaalu | last post by:
I am designing a matrix class that performs addition, multicpication, substraction and division. When ever i complie the code it shows an error. include <iostream> using namespace std; class matrix{ public: matrix();
11
7291
by: Stefano112 | last post by:
Hi, i'm making a matrix class, here is my code: #ifndef MATRICE_H #define MATRICE_H #include <iostream> template <class T> class matrice { public:
0
8761
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9280
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9142
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8144
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6016
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.