Interpolating an array to fit another size
Linearly interpolating a number between two numbers is a simple question, here is the wiki page.
one possible use of interpolation is increasing the resolution of a given discrete function.
What if we want to have another array with different size but same (linearly interpolated) fluctuations. In other words we want to squeeze or extend a given array using linear interpolation.
To give an example Lets say we have an array [1,5,3] and we want to have another array with the size of 5 produced from the given array, keeping its increase-decrease pattern. the result should be [1,3,5,4,3].
here is my solution
I just wanted to take a note not to forget 😉
// atPoint:[0,1]
function linearInterpolate(before, after, atPoint) {
return before + (after - before) * atPoint;
};
function interpolateArray(data, fitCount) {
var newData = new Array();
var springFactor = new Number((data.length - 1) / (fitCount - 1));
newData[0] = data[0]; // for new allocation
for ( var i = 1; i < fitCount - 1; i++) {
var tmp = i * springFactor;
var before = new Number(Math.floor(tmp)).toFixed();
var after = new Number(Math.ceil(tmp)).toFixed();
var atPoint = tmp - before;
newData[i] = this.linearInterpolate(data[before], data[after], atPoint);
}
newData[fitCount - 1] = data[data.length - 1]; // for new allocation
return newData;
};
the javascript code above changes the size of an given array to given fitCount and protects its fluctuation pattern. It could be pretty useful if you want to have a higher resolution array (in terms of its fluctuation pattern) from a small array.