471,336 Members | 1,254 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,336 software developers and data experts.

number of element in array/matrix


On Jan 11, 2008, at 11:09 AM, m.*******@durham.ac.uk wrote:
>
Hi,
I have what I suspect to be a fairly simple problem while using
python Numeric.
I am attempting to count the number of times that an element 'b'
occurs in
numeric array 'a'. I tried unsuccessfully to find a more efficient
function to
do this for me such as that offered when using a list, but couldn't
seem to find
anything for Numeric arrays. However, I suspect that my loop is not
the most
efficient way to achieve this.

def countel(a, b): #counts the number of times value 'b' is found
in array 'a'
i=0
count=0
while (i<len(a)):
j=0
while (j<len(a[0])):
if (a[i][j]==b):
count=count+1
else:
pass
j=j+1
i=i+1
return count

Any help or advice would be greatly appreciated,
Matt
something like this?
>>import numpy as n
a = n.matrix([[1,2,3,4,1],[2,3,4,1,2],[3,4,1,2,3]],"float")
a
matrix([[ 1., 2., 3., 4., 1.],
[ 2., 3., 4., 1., 2.],
[ 3., 4., 1., 2., 3.]])
>>k = n.where(a==1,1,0)
k
matrix([[1, 0, 0, 0, 1],
[0, 0, 0, 1, 0],
[0, 0, 1, 0, 0]])
>>k.sum()
4
>>>
Cheers
Tommy
Jan 11 '08 #1
0 778

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by Björn | last post: by
13 posts views Thread by mike | last post: by
12 posts views Thread by rajus | last post: by
272 posts views Thread by Peter Olcott | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.