代码之家  ›  专栏  ›  技术社区  ›  s28

计算并绘制数组中每N个值的梯度

  •  1
  • s28  · 技术社区  · 11 月前

    是否可以使用 np.gradient 计算给定数组中每10个值的梯度?

    rand = np.random.randint(low=1, high=10, size=(100,))
    

    注: 我想计算两次梯度。一旦之间 每个值 一次之间 每10个值 。然后我想把两者都画出来。这10个值应出现在每十个位置。这就是为什么我一开始似乎无法提取值。

    1 回复  |  直到 11 月前
        1
  •  2
  •   Bhargav    11 月前

    首先计算每个值之间的梯度

    import numpy as np
    import matplotlib.pyplot as plt
    
    rand = np.random.randint(low=1, high=10, size=(100,))
    gradient_full = np.gradient(rand)
    

    计算每10个值之间的梯度

    rand_10th = rand[::10]
    gradient_10th = np.gradient(rand_10th)
    

    创建绘图

    x_full = np.arange(100)
    x_10th = np.arange(0, 100, 10)
    

    情节

    plt.figure(figsize=(12, 6))
    
    plt.plot(x_full, gradient_full, label='Gradient (every value)', alpha=0.7)
    plt.plot(x_10th, gradient_10th, 'ro-', label='Gradient (every 10th value)', markersize=8)
    
    plt.xlabel('Index')
    plt.ylabel('Gradient')
    plt.title('Comparison of Gradients')
    plt.legend()
    plt.grid(True)
    
    plt.show()
    

    输出 enter image description here