Home > Net >  How to iterate over the rows of a table with p5js using table.setNum()
How to iterate over the rows of a table with p5js using table.setNum()

Time:08-03

function saveAsCSV() {
  
  let simulationOutput = new p5.Table();

  let newRow = simulationOutput.addRow();
  
  simulationOutput.addColumn("Total Population");
  simulationOutput.addColumn("Human Population");
  simulationOutput.addColumn("Predator Population");
  simulationOutput.addColumn("Prey Population");
  simulationOutput.addColumn("Food Population");

  for(var i = 1; i<totalDynamic.length; i  ){
    simulationOutput.addRow().setNum("Total Population", int(totalDynamic[i]));
  }
  
  for(let j = 1; j<predDynamic.length; j  ){
    simulationOutput.setNum(j,1, int(predDynamic[j]));
    j  ;
  }
  
  save(simulationOutput, month() "/" day() "_T:" hour() ":" minute() ":" second() "_Simulation_Output.csv");
}

I'm looking to save the outputs of a simulation to a .csv file, but I can't seem to iterate over the rows of the table using the for loop. I'm using p5.js

for(let j = 1; j<predDynamic.length; j  ){
    simulationOutput.setNum(j,1, int(predDynamic[j]));
    j  ;}

I get the following error:

Uncaught TypeError: Cannot read properties of undefined (reading 'setNum')
    at o.default.Table.setNum (p5.min.js:3:593463)
    at o.default.Element.saveAsCSV (predator_prey.js:255:22)
    at o.default.Element.<anonymous> (p5.min.js:3:429692)

The problem is with iterating using the j, but I can't see how this returns undefined?

CodePudding user response:

You get this error because totalDynamic.length < predDynamic.length

A row is added for each item in totalDynamic and not predDynamic. But when there are more items in predDynamic than totalDynamic, The p5.Table() doesn't recognize the rows because they haven't been initialized yet. Possible solution:

for(let j = 1; j<predDynamic.length; j  ){
   if(simulationOutput.rows.length <= j) simulationOutput.addRow();
   simulationOutput.setNum(j,1, int(predDynamic[j]));
   j  ;
}
  • Related