#### Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

# How Does Mapping Function work?

edited May 2017

Namaste all,

I wanted to know how does the map(); function actually works.

I did come across that for "variable2 = map(variable1, min1, max1, min2, max2);" we apply the formula "variable2 = min2+(max2-min2)*((variable1-min1)/(max1-min1))".

But how did we come to this?And does processing sole this by using matrices? If yes then how

Thanks a lot.

Tagged:

• edited June 2017 Answer ✓

`map` translates a variable variable1 from one range A to another range B and stores the result into variable2:

`variable2 = map(variable1, min1, max1, min2, max2)`

• range A is defined by min1, max1

• range B is defined by min2, max2

Let's say you want to translate your mouseX from the screen 0 to 1000 (width) to degree 0..360 use `map`.

Let's say variable would use 40 % on range A (so 400 pixels on the range of 1000) it would also use 40 % on range B (360 degree), but this value transformed to the new value for 40 % on range B (which gives you 144 degree on a range of 360 degree).

Another example, this time as code:

``````void setup() {
size(400, 400);
noStroke();
}

void draw() {
background(204);

fill(0);
text("red = mouse pos X, blue = the map result from 150 to 250", 16, 16);

fill(255, 0, 0);
ellipse(mouseX, 75, 50, 50);

float  x1 = map(mouseX, 0, width, 150, 250);
fill(0, 0, 255);
ellipse(x1, 175, 50, 50);
}
``````

https://www.processing.org/reference/map_.html

• Here:

The source:

``````  static public final float map(float value,
float start1, float stop1,
float start2, float stop2) {
float outgoing =
start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1));
if (outgoing != outgoing) {
badness = "NaN (not a number)";

} else if (outgoing == Float.NEGATIVE_INFINITY ||
outgoing == Float.POSITIVE_INFINITY) {
}
final String msg =
String.format("map(%s, %s, %s, %s, %s) called, which returns %s",
nf(value), nf(start1), nf(stop1),
PGraphics.showWarning(msg);
}
return outgoing;
}
``````

My favorite part is setting badness to infinity. Without the error checking, it is really just:

``````start2 + (stop2 - start2) * ((value - start1) / (stop1 - start1))
``````
• Thanks a lot @Chrisir and @jeremydouglass . It will take me some time to understand that piece of code jeremy, but thanks a ton. cheers. and apologies for the late reply.

• Glad it was helpful, @p2b2. The explanation from @Chrisir combined with the one-line version of the code should tell you most of what you need to know!