Mapping a value in BASH: Difference between revisions

From XPUB & Lens-Based wiki
(Created page with "A typical operation with (re)processing data for visualisation or other manipulation is the translation of some value (number) from one context to another. (In math terms you ...")
 
(for christoph / lafkon)
 
Line 17: Line 17:
echo out $out
echo out $out
</source>
</source>
[[Category: BASH]][[Category: Cookbook]]

Latest revision as of 12:12, 17 April 2014

A typical operation with (re)processing data for visualisation or other manipulation is the translation of some value (number) from one context to another. (In math terms you call this a mapping from a domain to a range.) In the BASH this can be tricky as maths are limited to being integer only -- so trying to work with a value like 0.5 won't work. In the example shown, the value 100 is used to multiply the input value to get a bit more precision. A higher value could be used for more precision (like 1000, 1000000). If this number is too big though (depending on the input / output numbers) you could get into trouble.

# map some value from inlo to inhi to a new range: outlow, outhi
function map {
  i=$1
  inlo=$2
  inhi=$3
  outlo=$4
  outhi=$5
  p=$(( (i*100) / (inhi-inlo) ))
  o=$(( outlo + (p * (outhi-outlo) / 100) ))
  echo $o
}

out=`map 50 0 100 5000 10000`
echo out $out