hey guys
I'm new to python... and I would like to know how do I create a matrix in python, if anyone can help, it would be appreciated. Thanx
1 9697 bvdet 2,851
Expert Mod 2GB
A matrix or array can be represented by a list of lists.
Example: - >>> [[0 for _ in range(3)] for _ in range(3)]
-
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
-
>>>
You can encapsulate an array object as an instance of a class object. Example: - class Matrix(object):
-
def __init__(self, rows, cols):
-
self.rows = rows
-
self.cols = cols
-
# initialize matrix and fill with zeroes
-
self.data = [[0 for _ in range(cols)] for _ in range(rows)]
-
-
def __setitem__(self, pos, v):
-
self.data[pos[0]][pos[1]] = v
-
-
def __getitem__(self, pos):
-
return self.data[pos[0]][pos[1]]
-
-
def __iter__(self):
-
for row in self.data:
-
yield row
-
-
def len(self):
-
return len(self.data)
-
-
def __str__(self):
-
return '\n'.join(['Row %s = %s' % (i, self.data[i]) for i in range(self.rows)])
-
-
def __repr__(self):
-
return 'Matrix(%d, %d)' % (self.rows, self.cols)
-
-
# Example
-
>>> m0 = Matrix(4,4)
-
>>> m0
-
Matrix(4, 4)
-
>>> print m0
-
Row 0 = [0, 0, 0, 0]
-
Row 1 = [0, 0, 0, 0]
-
Row 2 = [0, 0, 0, 0]
-
Row 3 = [0, 0, 0, 0]
-
>>> m0[3,3]='a string'
-
>>> m0[2,2]=123456
-
>>> print m0
-
Row 0 = [0, 0, 0, 0]
-
Row 1 = [0, 0, 0, 0]
-
Row 2 = [0, 0, 123456, 0]
-
Row 3 = [0, 0, 0, 'a string']
-
>>>
Another example using a dictionary: - class Darray(object):
-
-
def __init__(self, rows, cols):
-
self.rows = rows
-
self.cols = cols
-
# initialize array and fill with zeroes
-
self.data = {}
-
for row in range(rows):
-
for col in range(cols):
-
self.data.setdefault(row, {})[col] = 0
-
-
def __setitem__(self, rowcol, v):
-
self.data[rowcol[0]][rowcol[1]] = v
-
-
def __getitem__(self, rowcol, v):
-
return self.data[rowcol[0]][rowcol[1]]
-
-
def __str__(self):
-
outputList = ['%s%s%s' % ('Row/Col'.center(11), '|', ''.join(['%6s' % i for i in range(0,self.cols)])),]
-
outputList.append('=' * 6 * (2+self.cols))
-
for key in self.data:
-
outputList.append('%s|%s' % (str(key).center(11), ''.join(['%6s' % self.data[key][i] for i in self.data[key]])))
-
return '\n'.join(outputList)
-
-
if __name__ == '__main__':
-
print
-
a = Darray(4,6)
-
print a
-
print
-
a[3,4]=19
-
a[3,2]=344
-
a[0,5]=55
-
print a
Output from above example: - >>>
-
Row/Col | 0 1 2 3 4 5
-
================================================
-
0 | 0 0 0 0 0 0
-
1 | 0 0 0 0 0 0
-
2 | 0 0 0 0 0 0
-
3 | 0 0 0 0 0 0
-
-
Row/Col | 0 1 2 3 4 5
-
================================================
-
0 | 0 0 0 0 0 55
-
1 | 0 0 0 0 0 0
-
2 | 0 0 0 0 0 0
-
3 | 0 0 344 0 19 0
-
>>>
If you need more power and efficiency, you can install NumPy to create multi-dimensional arrays. Example: - >>> ar = numpy.array(((0,0,0,0), (1,2,3,4), (5,6,7,8)), float)
-
>>> ar
-
array([[ 0., 0., 0., 0.],
-
[ 1., 2., 3., 4.],
-
[ 5., 6., 7., 8.]])
-
>>> ar[:2]
-
array([[ 0., 0., 0., 0.],
-
[ 1., 2., 3., 4.]])
-
>>> ar[1:]
-
array([[ 1., 2., 3., 4.],
-
[ 5., 6., 7., 8.]])
-
>>> ar[1]
-
array([ 1., 2., 3., 4.])
-
>>>
Sign in to post your reply or Sign up for a free account.
Similar topics
by: François Miville-Dechêne |
last post by:
I find your language very nice, it is actually more than three quarters
of what I had been dreaming for years a programming language should be.
But I mourn the passing of APL, another interpreted...
|
by: Carl |
last post by:
I have been using Python for quite some time now and I love it. I use it
mainly for explorative computing and numerical prototyping, ie testing and
trying out different kinds of algorithms and...
|
by: Roman Suzi |
last post by:
Hi,
I wonder, does Python support generic programming paradigm, and to what extent
(I guess, it doesn't do it in full)? And (or) does it move in that direction?
Will we ever see
concept...
|
by: Nils Wagner |
last post by:
Hi all,
Has someone written a C binding to transfer matrices from C to Python
and vice versa ?
Any pointer would be appreciated.
Nils
|
by: Iwan van der Kleyn |
last post by:
Please ignore if you are allergic to ramblings :-)
Despite a puritan streak I've always tried to refrain from language wars
or syntax bickering; call it enforced pragmatism. That's the main...
|
by: C. Barnes |
last post by:
Hi, I'm in the process of writing a Python linear
algebra module.
The current targeted interface is:
http://oregonstate.edu/~barnesc/temp/linalg/
The interface was originally based on...
|
by: Zhengzheng Pan |
last post by:
Hi all,
I'm trying to check whether a (stochastic/transition) matrix
converges, i.e. a function/method that will return True if the input
matrix sequence shows convergence and False otherwise....
|
by: mosi |
last post by:
Python matrices are usually defined with numpy scipy array or similar.
e.g.
I would like to have easier way of defining matrices,
for example:
Any ideas how could this be done? The ";" sign...
|
by: Jordan |
last post by:
Hi everyone,
I'm a big Python fan who used to be involved semi regularly in
comp.lang.python (lots of lurking, occasional posting) but kind of
trailed off a bit. I just wrote a frustration...
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
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,...
|
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...
|
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...
|
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...
|
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,...
| |