Prompted by the recent Hough transform thread, I looked for a "rescale" verb in
the system library that would take a set of data and linearly rescales it to a
different range. I didn't find one and wondered if it might be a useful
addition.
Admittedly it is a pretty simple thing to reimplement but it seems like a task
that would come up reasonably frequently.
Here is a stab at one. Any ideas/suggestions for improvement?
NB.*rescale v Linearly rescales data to new range
NB. usage: [targetrange [,targetmin]] rescale data[;min,max]
NB. y is: numeric array
NB. Or 2-item boxed list containing
NB. 0{:: numeric data array
NB. 1{:: 2-item numeric list: the minimum and maximum possible values for
data
NB. x is: optional 1- or 2-item numeric list
NB. eg: 15 rescale 8 4 9 5 3.5 7;0 10
rescale=: 3 : 0
1 rescale y
:
'data minmax'=. 2{. boxopen y
'trange tmin'=. 2{. x
'smin smax'=. (<./ , >./) minmax,,data
data=. data %&(-&smin) smax
tmin + trange * data
)
rescale 4 1 9 5 3.5 7 NB. obtains min & max from data
0.375 0 1 0.5 0.3125 0.75
rescale 4 1 9 5 3.5 7;0 10 NB. give min & max possible vals if not in
data
0.4 0.1 0.9 0.5 0.35 0.7
15 rescale 4 1 9 5 3.5 7;0 10 NB. "out-of-10" to "out-of-15"
6 1.5 13.5 7.5 5.25 10.5
15 _5 rescale 4 1 9 5 3.5 7;0 10 NB. "out-of-10" to "from _5 to 10"
1 _3.5 8.5 2.5 0.25 5.5
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm