[SciPy-user] Creating a Matrix from a Sum

Tom K. tpk@kraussfamily....
Fri Jul 3 12:35:51 CDT 2009



Lorenzo Isella wrote:
> 
> I need some help to efficiently write an array manipulation. I suspect 
> this could be a one-liner.
> Assume that you have a histogram of observations that you store in a 
> vector x.
> Let us say that its i-th entry, x_i, corresponds to the number of 
> observations in the i-th channel, for i=1,2...N. (or 0,1...N-1, please 
> let me know if there is any potential 0/1 pitfall in the following).
> Now, for any two channels i and j, I want to calculate the probability 
> of having an observation  in any other channel k, where  k>=max(i,j).
> That is to say
> 
> P(i,j)=sum_{k=max(i,j)}^N x_k /C,
> where C=sum_{i=1}^N x_i is just a normalization factor.
> 
> Does anyone know a good way of writing this in a code to get the P(i,j) 
> matrix?
> 

I'm not sure about a 1 liner.

Here are two ways that work:

1) Accumulate the array starting with the last element.
P = np.zeros((len(x), len(x)))
i = len(x)
for xi in x[::-1]:
    P[:i, :i] += xi
    i -= 1

2) Index into the reversed cumulative sum with a max_ij array.
i = np.arange(len(x))[:,np.newaxis]
j = np.arange(len(x))
max_ij = np.maximum(i,j)
P = x[::-1].cumsum()[::-1][max_ij]



-- 
View this message in context: http://www.nabble.com/Creating-a-Matrix-from-a-Sum-tp24306698p24326539.html
Sent from the Scipy-User mailing list archive at Nabble.com.



More information about the SciPy-user mailing list