简体   繁体   中英

Quick way to interpolate between matrices? (using numpy arrays)

I now have a lot of matrices (m rows and n columns), I want to get the "intermediate matrix" of these matrices, and I want to do interpolation. I know how to write my program with a for loop, but it is too slow! Each matrix has about several million elements, and I want to interpolate over 20 matrices to get at least three times the original number of matrices among them. If I use a loop, the calculation speed is very slow. I want to know if there are any advanced methods.

Do you use vectorized forms? NUMPY is the most common approach. But you might use NUMBA or CUDA too, depending on your environment

import numpy as np

nm = 3  # number of matrices
ns = 3 # size of matrices

def generate_matrices(ns, nm):
    return np.array([(i*i)*np.ones((ns,ns)) for i in range(nm)])

#---- generate data matrices ----
A = generate_matrices(ns, nm)
print('A'); print(A);print()

#---- interpolate thee matrices -------
t0 = 0.4
t1 = 1 - t0

for jm in range(1,nm):
    B = t0*A[jm-1] + t1*A[jm]
    print('jm = ', jm); print(B); print()


A
[[[0. 0. 0.]
  [0. 0. 0.]
  [0. 0. 0.]]

 [[1. 1. 1.]
  [1. 1. 1.]
  [1. 1. 1.]]

 [[4. 4. 4.]
  [4. 4. 4.]
  [4. 4. 4.]]]
jm =  1
[[0.6 0.6 0.6]
 [0.6 0.6 0.6]
 [0.6 0.6 0.6]]

jm =  2
[[2.8 2.8 2.8]
 [2.8 2.8 2.8]
 [2.8 2.8 2.8]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM