Trainable template search algorithm for efficient signal processing