Han Zhengzu
Han Zhengzu

Reputation: 3842

Find an easier way to compare two 2-d array's independence

My question

1. Intro

Using np.mask, they shows like this:

http://i4.tietuku.com/29adccd90484fe34.png
code here:

ka_select = np.ma.masked_less(ka,0.001)
pa =plt.pcolor(kb_select,cmap="Set1",alpha =0.7,facecolor = "k",edgecolor = 'k',zorder =1)
kb_select = np.ma.masked_less(kb,0.001)
pb =plt.pcolor(kb_select,cmap="Set1",alpha =0.7,facecolor = "k",edgecolor = 'k',zorder =1)         

2. My early work

I have written some code about comparing two 2-d array

### repeat I defined is the estimate matrix to represent overlap or not in [i,j] position
repeat = np.zeros(ka.shape[0]*ka.shape[0]).reshape(ka.shape[0],ka.shape[1])

for i in range(0,ka.shape[0],1):
    for j in range(0,ka.shape[1],1):
        if (ka[i,j] == 1) & (kb[i,j] == 1) :
           repeat [i,j]=1
         else:
            repeat[u,v]  = 0
rep.append(repeat.sum())

http://i4.tietuku.com/7121ee003ce9d034.png

3. My question

When there are more than two 2-d numpy array all in the same shape with value (0,1), How to sum the overlapping frequency?
I can compare multi array in sequence but the repeat grid would be re-counted

More explain

I want to sum the amount of array ka when ka = 1 but (kb & kc & ...) != 1 at grid[i,j] (Which I call it independence as shown in title).
If ka only comparing with kb, I can use rep to achieve that, and I haven't thought out the method dealing with more than 2 array

Upvotes: 2

Views: 121

Answers (1)

Niemerds
Niemerds

Reputation: 942

Why not using the sum of the arrays kb, ... and test the resulting elements? An example with three grids:

import numpy

# some random arrays
ka = numpy.random.random_integers(0,1,37*31).reshape(31,37)
kb = numpy.random.random_integers(0,1,37*31).reshape(31,37)
kc = numpy.random.random_integers(0,1,37*31).reshape(31,37)
combined_rest = kb + kc

print "independance:", numpy.sum( (ka == 1) & (combined_rest < 2) )

Upvotes: 3

Related Questions