0

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.

2 Answers 2

2

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)]);
}
Sign up to request clarification or add additional context in comments.

Comments

0
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.

2 Comments

can I just ask why the for loop condition has '!=targetValue + 1' as a condition?
The second statement (x != targetValue + 1) is for ending the loop if it returns false. So, if x reaches 10, the loop would stop without executing y(10) because x != 10 is false. That's why I'm adding the startingValue to the targetValue. In most cases you would start by zero (for(var i = 0;...)). But i != targetValue + 0 does not make sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.