1

I'm learning how to code and I didn't quite understand how a class really works. If I create a matrix for example:

class Matrix(object):

 def __init__(self,i,j,value):
  self.rows = i
  self.cols = j
  self.value = value

if I have a random matrix and want to select the biggest value in a row, i can write:

for value in row

and the program will know I mean the value ij in the ith row?

Vini.g.fer
  • 11,639
  • 16
  • 61
  • 90
jnmf
  • 137
  • 1
  • 1
  • 8
  • If you are struggling with python classes, check out this question: http://stackoverflow.com/questions/6667201/how-to-define-two-dimensional-array-in-python And this one talks a bit about matrices http://stackoverflow.com/questions/6667201/how-to-define-two-dimensional-array-in-python Udacity also have some good starting courses on python. – Vini.g.fer Apr 12 '16 at 14:09
  • Is self.rows a list of rows (i.e. self.rows = ['dog','cat',hamster']), or is it an integer indicating the number of rows in your Matrix? – user1245262 Apr 12 '16 at 14:09
  • check this out: https://docs.python.org/2/tutorial/classes.html – Fabiano Apr 12 '16 at 14:38

3 Answers3

1

Usually in python Matrixes would be two dimensional arrays. Like:

matrix = [[11,12,13,14],[21,22,23,24],[31,32,33,34]]

//is the same as

would give you a matrix like:

11 12 13 14 
21 22 23 24
31 32 33 34

so you have an array which stores the rows (the outer array) and one array for each row. To access e.g. the value at position (2,4) which is 24 you would do

matrix[1][3]

as matrix[1] = [21,22,23,24] and matrix[1][3] = [21,22,23,24][3] = 24

To iterate over your matrix (i.e. your two dimensional array) you can do:

#iterate over the rows
for row in matrix:
    #max value
    max = max(row)
    print max
    #if you want to iterate over the elements in the row do:
    for element in row:
        print element

In Your example you are defining a Matrix class which will be initialized with 3 parameters: i, j and value. You are not doing more. For examples of your own matrix class you could have a look here

niklas
  • 2,887
  • 3
  • 38
  • 70
0

Use enumerate to interpolate indexes:

>>> for i, j in enumerate(["a","b","c"]):
...   print i, j
... 
0 a
1 b
2 c

In your case:

# suppose m is an instance of class Matrix
for i, row in enumerate(m.value):
    for j, ele in enumerate(row):
        # find greatest and halt
        # i, j are the expected index
        yeild i, j

To find a largest element from a list there are multiple ways, for example: Pythonic way to find maximum value and its index in a list?

However, more clever way is to utilize numpy.matrix if programming yourself is not necessary.

Community
  • 1
  • 1
knh170
  • 2,960
  • 1
  • 11
  • 17
0

The

for value in row

code will NOT get you the biggest value in the row. It will just iterate (run through) each item in the row (once you define row of course). You need to add a check to get the biggest number.

Vini.g.fer
  • 11,639
  • 16
  • 61
  • 90