For loop to find largest number in table column.

For loop to find largest number in table column.

kari_payton
Not applicable
954 Views
6 Replies
Message 1 of 7

For loop to find largest number in table column.

kari_payton
Not applicable

[ FlexSim 17.2.1 ]

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;

8412-tablecodehelp.png

0 Likes
Accepted solutions (1)
955 Views
6 Replies
Replies (6)
Message 2 of 7

Matthew_Gillespie
Autodesk
Autodesk
Accepted solution

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



Matthew Gillespie
FlexSim Software Developer

0 Likes
Message 3 of 7

kari_payton
Not applicable

@Matthew Gillespie

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

0 Likes
Message 4 of 7

Matthew_Gillespie
Autodesk
Autodesk

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)



Matthew Gillespie
FlexSim Software Developer

Message 5 of 7

Matthew_Gillespie
Autodesk
Autodesk

You could also do this very easily with a query:

return Table.query("SELECT * FROM MainDataTable ORDER BY [Col 1] DESC")[1][1];


Matthew Gillespie
FlexSim Software Developer

0 Likes
Message 6 of 7

kari_payton
Not applicable

ok got it. Thanks @Matthew Gillespie

0 Likes
Message 7 of 7

mischa_spelt
Advisor
Advisor

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);