# Add different results into a variable

## Recommended Posts

Hi guys,

i have a problem to calculate the average of some results with a tcl script. Perhaps someone could help me here.

I export from HyperGraph pressure results of some nodes of a transient simulation (normally i export 20-50 nodes with 50-100 time steps).

A simple example can  you see in the following excel picture.

Before the comma, there is the time step, after the comma the pressure.

The differnt nodes are seprate by an empty raw. (In this example there a three nodes)

How can i add the different pressures, to get the average pressure of all nodes?

I think the first step is, to spilt every raw by the comma.

The following picture shows my current script.

I think "append" is not the right command for this problem.

Has anyone a proposal???

Thank you and best regards

Michael

##### Share on other sites

Maybe use lappend instead of append?

##### Share on other sites

Hi tinh,

With lappend i create a list, but i want to calculate the average.

I would like to calulate the sum of the pressure of every first time steps [(p11+p12+p13)/3] , the sum of every second time steps [(p12+p22+p32)/3], the sum of the third time steps [(p13+23+33)/3],  and so on...

Do you know what i meaning?

Perhaps this Problem could be solved with Loops?

Thank you and best regards

Michael

##### Share on other sites

Yes, I understand.

you have to loop for each node, example:

```foreach i {1 2 3 4 5} {set SumP\$i 0}

File2Buff \$dir buff

set Count 0

foreach {line1 line2 line3 line4 line5 emptied} [split \$buff \n] {

incr Count

foreach i {1 2 3 4 5} {

set P\$i [lindex [split [set line\$i] ,] 1]
set SumP\$i [expr [set SumP\$i]+[set P\$i]]

}

}

foreach i {1 2 3 4 5} {

puts "Avg pressure at step \$i = [expr 1.0*[set SumP\$i]/\$Count]"

}```

mkress likes this

##### Share on other sites

Hi tinh,

Unfortunately, i get an error from the last line...

It is the line:               puts "Avg pressure at step \$i = [expr ﻿1.0*[set SumP\$i]/\$Count]"﻿﻿﻿﻿

I don´t understand this error. There are no characters???

Is it also possible to write for "1 2 3 4 5" in "foreach i {1 2 3 4 5﻿﻿}"   a variable \$number_time_steps?

This would be important because i have always different numbers of time steps (50-100 steps).

Thank you very much!

Michael

##### Share on other sites

Maybe, you copy & paste my code. Be not lazy, type it again!

Instead of foreach, you can use 'for' loop.

## Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

×   Pasted as rich text.   Paste as plain text instead

Only 75 emoji are allowed.