user1821176
user1821176

Reputation: 1191

Summing the indexes from a generated list of arrays

Hello I have list of arrays generated from a defined function below. I am wondering if there is way to sum up the same index in each array in the list giving me only 1 array?

import numpy as np       
Tsp = np.linspace(3500, 40000, 3)
wcm = np.linspace(100, 10000, 5)    
def blackbody(T, wcm):
    k = 1.38*10**-16.0 #ergs/k                                                  
    h = 6.625*10**-27.0 #erg/s                                                  
    c = 3*10.0**10.0 #cm/s                                                      
    bbtop = (2.0*h*c**2.0)
    bbbot = (wcm**5.0)*(np.exp((h*c)/(wcm*k*T)) - 1)
    bbs = bbtop/bbbot
    return bbs

outflux = [blackbody(T_i, wcm) for T_i in Tsp]

Upvotes: 1

Views: 60

Answers (1)

Daniel
Daniel

Reputation: 19547

Change the definition to:

def blackbody(T, wcm):
    k = 1.38*10**-16.0 #ergs/k
    h = 6.625*10**-27.0 #erg/s
    c = 3*10.0**10.0 #cm/s
    bbtop = (2.0*h*c**2.0)

    T = np.atleast_1d(T)       #So you can pass a single number if desired.
    bbbot = (wcm**5.0)*(np.exp((h*c)/(wcm*k*T[:,None])) - 1) #Changed T to T[:,None]
    bbs = bbtop/bbbot
    return bbs

Now you can call it as:

blackbody(Tsp, wcm)

Double check that they are equal:

looped = np.array([blackbody(T_i, wcm) for T_i in Tsp])
broadcast = blackbody(Tsp, wcm)

print np.allclose(looped,broadcast)
True

Now that you have a single array you can sum on the axis you need using np.sum:

data = blackbody(Tsp, wcm)
data
[[  2.89799404e-10   6.59157826e-16   4.45587348e-17   9.03800033e-18
    2.89799993e-18]
 [  1.80089940e-09   4.09619532e-15   2.76900716e-16   5.61647169e-17
    1.80089999e-17]
 [  3.31199940e-09   7.53323285e-15   5.09242710e-16   1.03291433e-16
    3.31200005e-17]]

np.sum(data,axis=1)
[  2.89800119e-10   1.80090385e-09   3.31200758e-09]

np.sum(data,axis=0)
[  5.40269821e-09   1.22885860e-14   8.30702161e-16   1.68494151e-16
   5.40270004e-17]

The data is aligned in both axes, but im not sure which you want from your question.

Upvotes: 2

Related Questions