| | |
Find centroid in a 2d array (list of lists)
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Jul 2008
Posts: 39
Reputation:
Solved Threads: 0
Hi,
my question is how I can find the centroid of group of cells that share the same value. Say I have this:
I need to get the centroid in x and y = (1.875, 2)
I tried to iterate over all values and when this is 1 store all the x and y coordinates but im stucked as how to actually get the centroid of these points.
my question is how I can find the centroid of group of cells that share the same value. Say I have this:
Python Syntax (Toggle Plain Text)
grid = [[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0 ,0, 0]]
I need to get the centroid in x and y = (1.875, 2)
I tried to iterate over all values and when this is 1 store all the x and y coordinates but im stucked as how to actually get the centroid of these points.
•
•
Join Date: Jul 2006
Posts: 608
Reputation:
Solved Threads: 150
You mean the center of mass?
Well, do it like the physicists do: Sum(moments) / Sum(masses):
Jeff
Well, do it like the physicists do: Sum(moments) / Sum(masses):
Python Syntax (Toggle Plain Text)
>>> def findCOM(grid): Mx = 0 My = 0 mass = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j]: Mx += j My += i mass += 1 COM = (float(Mx)/mass , float(My)/mass) return COM >>> grid = [[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 0, 0], [0, 1, 1, 1, 0], [0, 0, 0 ,0, 0]] >>> findCOM(grid) (1.875, 2.0) >>>
Jeff
![]() |
Other Threads in the Python Forum
- Previous Thread: Start remote file with associated application
- Next Thread: Printing words that begin within capital letters
Views: 1001 | Replies: 2
| Thread Tools | Search this Thread |
Tag cloud for Python
advanced anydbm app bash beginner bits calling chmod cmd code data dictionary directory dynamic edit examples excel external feet file float format ftp function gui homework http i/o images import info input ip itunes java keycontrol line linux list lists loan loop maintain millimeter mouse newb number numbers output panel parsing path port prime print program programming projects push py-mailer py2exe pygame pyqt python queue random rational recursion recursive scrolledtext smtp split ssh string strings sudokusolver table terminal text thread threading time tkinter tlapse tuple tutorial ubuntu unicode update urllib urllib2 variable variables ventrilo web webservice whileloop windows wxpython xlib





