question

Kari Payton avatar image
0 Likes"
Kari Payton asked Mischa Spelt commented

For loop to find largest number in table column.

Hi,

I need help writing a code that finds the highest value in a table's column. Here's my attempt but it returns a 0.

Table MainData = Table("MainDataTable");


int oldResult = 0;
int newResult = 0;


for( int row = 1; row<= Table("MainDataTable").numRows; row++)
	newResult = Table("MainDataTable")[row][1];
	if (newResult >= oldResult)
		oldResult = newResult;


return newResult;

FlexSim 17.2.1
code editor
tablecodehelp.png (5.4 KiB)
· 2
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

Matthew Gillespie avatar image Matthew Gillespie ♦♦ commented ·

You could also do this very easily with a query:

return Table.query("SELECT * FROM MainDataTable ORDER BY [Col 1] DESC")[1][1];
0 Likes 0 ·
Mischa Spelt avatar image Mischa Spelt Matthew Gillespie ♦♦ commented ·

Or, if you prefer not to use queries, you can use the findmax command (for more information, look it up in the command reference). For example, the following code assumes that you have a global table MyTable and want to find the maximum value in column 2:

Table table = Table("MyTable");
int maxOfColumn = 2;

// Returns the maximum value
return findmax(table.numRows, table[count][maxOfColumn]);

You can use the optional third parameter to return something else, for example if you want to know in which row the maximum occurs

// Returns the row containing the maximum value
return findmax(table.numRows, table[count][maxOfColumn], count);
2 Likes 2 ·

1 Answer

Matthew Gillespie avatar image
0 Likes"
Matthew Gillespie answered Kari Payton commented

You need to return oldResult, not newResult, since that is where you're storing the current biggest number.

· 3
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

Kari Payton avatar image Kari Payton commented ·

@Matthew Gillespie

I tried that but still get a 0.largesttablenumhelp.fsm

0 Likes 0 ·
Matthew Gillespie avatar image Matthew Gillespie ♦♦ Kari Payton commented ·

You need to put braces around everything you want the for loop to do, otherwise it just executes the first line over and over.

Table MainData = Table("MainDataTable");
int maxValue = 0;

for( int row = 1; row <= MainData.numRows; row++) {
	int curValue = MainData[row][1];
	if (curValue > maxValue)
		maxValue = curValue;
}
return maxValue;

(I renamed your variables for clarity)

1 Like 1 ·
Kari Payton avatar image Kari Payton Matthew Gillespie ♦♦ commented ·

ok got it. Thanks @Matthew Gillespie

0 Likes 0 ·