How do I interpolate within a 2d dataset?

Hi, thanks in advance for the help!

For those of you familiar with matlab, I’m simply trying to perform an interp1, but I can’t seem to find a similar function in javascript. I’m sure I’m just overlooking it, despite hours of research! Here’s my problem:

I’m importing a text file of data into a 2d array (though I’m open to suggestions otherwise) and I would like to input an x value and return an interpolated y value.

The text file looks something like this:

5 20

6 21

7 25

etc, etc.

In matlab I would simply write:

y = interp1(xdata,ydata,x)

where x is my input and y is my result. Any ideas on how to perform this in js?

Thanks again!!

So import the data into an array of float - use float.Parse(someStringValue) to convert it.

Then use Mathf.Lerp(value1, value2, aNumberBetween0and1) to get your result.

I didn’t really like the AnimationCurve solution Mike posted below. I suppose it could have worked, but it was not intended for what I was attempting to do – evaluate data. So I wrote a simple function that essentially mimics what Matlab’s interp1 does.

function InterpX(x){  //linearly interpret a Y value given an X input
	arraylength = dataPairs.length - 1;  // get # of rows of my array
	//Debug.Log(arraylength);

	for (var i = 0; i < arraylength; i++){  //start for loop to look through each data point
			var index = i; //save current value of i for use later since using i directly fucks it up
	        	        
	        //get x and y value for i position
        	var NumA = parseFloat(dataPairs*[0]);*

_ var NumC = parseFloat(dataPairs*[1]);*_

* //get x and y value from data for i + 1 position*
* if(index < arraylength){*
* var NumB = parseFloat(dataPairs[index + 1][0]);*
* var NumD = parseFloat(dataPairs[index + 1][1]);}*

* //find which data points our x input falls between*
* if (NumA < x && x < NumB){*
* var DeltaAB = Mathf.Abs(NumB - NumA); //Get difference between the two x values*
* var DeltaxAB = x - Mathf.Min(NumA,NumB); //Our input minus whichever value is lowest*
* var Ratio = DeltaxAB/DeltaAB; // ratio of our input to the span between A and B*
* Debug.Log(x + ’ is between ’ + NumA + ’ and ’ + NumB);*

* var DeltaCD = Mathf.Abs(NumD - NumC); //Get difference between the two y values*
_ var y = (DeltaCD * Ratio) + Mathf.Min(NumC,NumD); //Linear interpolation of y_
* Debug.Log(‘y:’ + y);*

* break; //end i loop*
* }*
* }*
} //end function InterpX
There may be more efficient ways to have written this function – and I’m open to suggestions to improve it – but all that really matters is that I can now process some data :smiley:
I wanted to post this in case anybody else is ever looking for a similar function. Of course the prerequisite prior to calling the function is that you have imported data from a file to an array which is called dataPairs here.
Thanks again for the help, Mike! Much appreciated.