Home > Software design >  if and else in Convolution function
if and else in Convolution function

Time:10-22

I have a problem with use if and else statement in convolution function.

this code return error:

use any() or all()

import matplotlib.pyplot as plt
import numpy as np

def name(y):
  if y<300 :
      print("if")
      fun2=y-6
      return fun2
  else:
      fun2=6-y
      print("else")
      return fun2

y=np.arange(1,1000,1) 
x=np.arange(1,1000,1)
fun1=np.sin(x)
con=np.convolve(fun1,name(y))
plt.plot(con)
plt.show()

how to can i use condition in convolve?

I hope you always good luck. thanks.

CodePudding user response:

The name function is called with a numpy array as the parameter. "Is the array less than 300?" isn't meaningful. Are all the items less than 300, np.all? Are any of them less than 300, np.any? My guess is that you want something like:

def name( y ):
    sign = 1 - 2*(y>300)
    return sign * (y-6)

y = np.arange( 290, 310 )
name( y )

# array([ 284,  285,  286,  287,  288,  289,  290,  291,  292,  293,  294,
#        -295, -296, -297, -298, -299, -300, -301, -302, -303])

This uses the boolean result for each item in the array to perform arithmetic and is one way of allowing different treatments for different elements in an array.

  • Related