Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 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)]);
}
share|improve this answer
    
That's awesome, thank you very much –  user3826598 Jul 10 '14 at 18:37
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.

share|improve this answer
    
can I just ask why the for loop condition has '!=targetValue + 1' as a condition? –  user3826598 Jul 10 '14 at 18:40
    
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. –  SVSchmidt Jul 10 '14 at 19:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.