I usually make a matrix like this

from Numeric import *
A=zeros([3,3])
print str(A[0,1]) #access an element

I would like to store a pair of values in each element, that is have a matrix where the (0,0) element is (2.3, 2.4), the (0,1) element is (5.6,6.7), etc.

Is this possible? I would like to access it using something like

A[0,1][0]
and
A[0,1][1]

Thanks!

Dave

Yeah, sure thing. I don't know if generating it will be as easy as your zeros but here's an example:

>>> mtrx = [[(0,0),(0,1),(0,2),(0,3)],
...         [(1,0),(1,1),(1,2),(1,3)],
...         [(2,0),(2,1),(2,2),(2,3)],
...         [(3,0),(3,1),(3,2),(3,3)]]
>>> mtrx[2][1]
(2, 1)
>>> mtrx[2][1][0]
2
>>> mtrx[2][1][1]
1
>>>

HTH

Thanks for the quick response! That'll work for now. However it doesn't scale particularly well (if I wanted a 1000x1000 matrix, I couldn't fill all those entries manually the first time!). Is there a way to initialize the matrix to a (0,0) pair for an arbitrary size?

Thanks,

Dave

you can try

mtrx = [[(0,0) for i in range(n)] for i in range(n)]

Where n is the size of the matrix on both dimensions.

If you want to use module Numeric, replace it with the newer module numpy ...

# create an array of tuples using module numpy
# module numpy historically evolved this way:
# numeric --> numarray --> numpy

import numpy as np

rows = 3
cols = 5

# create a 3 by 5 array of tuple zeroes (float is default)
z = np.zeros([rows, cols], tuple)

print z

print '-'*40

for row in range(rows):
    for col in range(cols):
        # assign tuple (0, 0) or whatever tuple
        z[row][col] = (0, 0)

print z

print '-'*40

# replace tuple at [1][1]
z[1][1] = (2.5, 3.5)

print z[1][1]

"""
my output -->
[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]]
----------------------------------------
[[(0, 0) (0, 0) (0, 0) (0, 0) (0, 0)]
 [(0, 0) (0, 0) (0, 0) (0, 0) (0, 0)]
 [(0, 0) (0, 0) (0, 0) (0, 0) (0, 0)]]
----------------------------------------
(2.5, 3.5)
"""
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.