Mailing List Archive: 49091 messages

## [REBOL] Re: Math Functions???

### From: larry:ecotope at: 10-May-2001 19:57

```
Hi Robert

>[ Conveniently a a convolve function would be very handy ;-> ]

> I was not looking forward to implementing this because of the level of
> nested for loops required. However in describing it on paper I think i've
> figured out an easy way to complete the task. Not very effecient mind...

The script below implements a simple convolution function. End values are
dropped, but you can pad the data block with zero's or modify the function
to do that. When large arrays are convolved, dropping the end values is
common. Some examples using Savitsky-Golay filters:

>> do %convolve.r
Script: "Convolution" (10-May-2001)

;the data to be processed
>> a: [1 2 3 4 5 4 3 2 1]
== [1 2 3 4 5 4 3 2 1]

; a convolution kernel for simple smoothing
>> b: [.25 .50 .25]
== [0.25 0.5 0.25]

>> convolve a b
== [2 3 4 4.5 4 3 2]

; a convolution kernel for first differences (numerical differention)
>> b: [1 -1]
== [1 -1]

>> convolve a b
== [-1 -1 -1 -1 1 1 1 1]

As you can see below, writing numerical code in REBOL is pretty easy, in
fact the code is not much different than in other languages.  But REBOL,
being an interpreter, tends to be very slow for large arrays.

HTH
-Larry

-------------------code--------------------------
REBOL [
Title: "Convolution"
Author: "Larry Palmiter"
File: %convolve.r
Version: 0.1.0
Date: 10-May-2001
Purpose: {A simple convolution function}
Comment: {
End values are dropped (one of a variety
of possible ways to treat the ends, i.e.
circular convolution, pad with 0, etc.)
}
]

convolve: func [data [block!] filter [block!] /local k m n out] [
n: length? data  m: length? filter
if m > n [exit]
out: copy []
repeat j n - m + 1 [
x: 0
k: j
repeat i m [
x: data/:k * filter/:i + x
k: k + 1
]
append out x
]
out
]
```