Thanks Martins, that did the magic. Thanks so much. I'm on the tutorials now. Regards.
On 29 Jul 2011 15:24, "Martin Ling" <[email protected]> wrote: > On Fri, Jul 29, 2011 at 02:55:15PM +0100, DIPO ELEGBEDE wrote: >> >> I have a 4 by 4 matrix filled with 0s, 1s and 2s. >> I want to loop through the whole matrix to get the fields with 1s and 2s >> only and then count how many ones and how many twos. > > Try this: > >>>> m = matrix('1,2,0,2;2,2,1,0;0,2,0,2;1,1,0,2') > >>>> m > matrix([[1, 2, 0, 2], > [2, 2, 1, 0], > [0, 2, 0, 2], > [1, 1, 0, 2]]) > >>>> sum(m == 1) > 4 >>>> sum(m == 2) > 7 > > This works because 'm == 1' evaluates to a boolean matrix whose elements > are true where that element of m is equal to 1: > >>>> m == 1 > matrix([[ True, False, False, False], > [False, False, True, False], > [False, False, False, False], > [ True, True, False, False]], dtype=bool) > > Calling sum() on this matrix adds up the number of true elements. > > I suggest you read the NumPy tutorial: > http://www.scipy.org/Tentative_NumPy_Tutorial > > This sort of thing is covered under 'Indexing with Boolean Arrays': > http://www.scipy.org/Tentative_NumPy_Tutorial#head-d55e594d46b4f347c20efe1b4c65c92779f06268 > > > > Martin > _______________________________________________ > NumPy-Discussion mailing list > [email protected] > http://mail.scipy.org/mailman/listinfo/numpy-discussion
_______________________________________________ NumPy-Discussion mailing list [email protected] http://mail.scipy.org/mailman/listinfo/numpy-discussion
