Reputation: 11
I'm looking to declare a function that can generate a series of ordered pairs of values within an array, such as can be plotted on a graph. I have two variables:
var xAxis = 1;
var yFunction = 4*(xAxis^xAxis) + 12(xAxis) + 20;
so, basically this would use Flot for JQuery to plot a quadratic equation on a graph, but I want to be able to use, say, a while loop to increment the xAxis
variable by one on every iteration, and then compute the yFunction
value for xAxis
on that iteration. I'm not sure how to keep yFunction
pegged to the present value of xAxis
.
Also, the function has to generate each value of xAxis
and yFunction for every iteration and then store these values into an array of the format:
var graphArray = [[1, 2], [2, 4], [3, 6], [4, 8]];
And from there, I can plot the graph.
If anyone has any idea how I would go about doing this, I'd be grateful. I've looked around forms and can see no obvious solution to my very specific problem.
Upvotes: 0
Views: 89
Reputation: 6537
function y(x) { //handle y as function as learned in school
return 4 * (Math.pow(x,x)) + 12 * x + 20;
}
var objValueTable = {}, //object to store data into
targetValue = 10; //value to iterate to
for(var x = 1; x != targetValue + 1; x++) {
objValueTable[x] = y(x); //store value of y at point x in object
}
should work well. See example via jsfiddle. targetValue is the number of iterations the function should do.
Upvotes: 0
Reputation: 18861
Your starting point is to define the yFunction
as a function:
var yFunction = function(x) {
return 4 * Math.pow(x, x) + 12 * x + 20;
}
// assuming that by x^x you meant X to the power of X.
Then your loop may be something like:
var graphArray = [];
for(var x = 1; x <= 4; x++) {
graphArray.push([x, yFunction(x)]);
}
Upvotes: 2