Search code examples
python-3.xnumpymatrixoptimizationvectorization

How to calculate a Kernel/Matrix efficiently


import numpy as np

solution_point_count = 150
impedance_datapoint_count = 134 

impedance_frequency = np.logspace(np.log10(100000), np.log10(0.0199), impedance_datapoint_count)
solution_frequency_logspace = np.logspace(np.log10(100000), np.log10(0.06), solution_point_count)
    
# Initializing zeros matrix to store results     
Z_RC = np.zeros((impedance_datapoint_count,solution_point_count))

#Constructing Debye Model for RC Kernel
#Debye Model: Z_RC = 1/(1 + iω*𝜏) where ω = 2πf and 𝜏 = RC = 1/(2πf)

for n in range(solution_point_count):
    for m in range(impedance_datapoint_count):
        Equation = 1/(1+1j*impedance frequency[m]/solution_frequency_logspace[n])
            Z_RC[m,n] = np.real(Equation) # Extracting real part only

While this works to create the kernel Z_RC, it is very slow and probably inefficient. Is there a more efficient way to do this? Perhaps with vectorization?


Solution

  • for n in range(solution_point_count):
        for m in range(impedance_datapoint_count):
            Equation = 1/(1+1j*impedance frequency[m]/solution_frequency_logspace[n])
                Z_RC[m,n] = np.real(Equation) # Extracting real part only
    

    should be calculable with 'broadcasted' arrays. Without testing I'd suggest

    Z_RC = (1 / (1 +1j * impedance_frequency[:,None] / 
        solution_frequency_logspace)).real
    

    This divides (m,1) array by a (n,) to produce a (m,n)