Sum the values in Array

9 views
Skip to first unread message

DINESH BABU

unread,
Apr 27, 2017, 6:20:31 AM4/27/17
to AMPL Modeling Language
Hi, 

I am trying to sum values in array (list of variables) like below. But I don't know how to do it AMPL. Could anyone help me how to do it in AMPL? 

a = (1,2,3,4,5,6)
result = (1, 3, 6, 10, 15, 21)
Thanks,
Dinesh.

Robert Fourer

unread,
Apr 28, 2017, 9:02:37 AM4/28/17
to am...@googlegroups.com
It is hard to say exactly what you should do, since you have not said how you want to define "a" and "result" in your AMPL model. But as an example, if you have defined "param a {1..6};" and "param result {1..6};" then you can write

let {i in 1..6} result[i] := sum {j in 1..i} a[j];

or

let {i in 1..6} result[i] := if i=1 then a[1] else result[i-1] + a[i];

These are just two ways of getting the same result.

Bob Fourer
am...@googlegroups.com

=======

Dinesh Babu Seenivasan

unread,
Apr 28, 2017, 10:26:26 AM4/28/17
to am...@googlegroups.com
Hi Robert,

"a" is output and it's have list of parameters. Now I am doing this in Excel and I have attached it here. If you check it, you can understand what I am trying do it ampl.  

Thanks,
Dinesh.

--
You received this message because you are subscribed to a topic in the Google Groups "AMPL Modeling Language" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/ampl/DL2p5HAVGig/unsubscribe.
To unsubscribe from this group and all its topics, send an email to ampl+unsubscribe@googlegroups.com.
To post to this group, send email to am...@googlegroups.com.
Visit this group at https://groups.google.com/group/ampl.
For more options, visit https://groups.google.com/d/optout.

Time.xlsx

Robert Fourer

unread,
Apr 29, 2017, 12:03:09 PM4/29/17
to am...@googlegroups.com
You might define in your AMPL model,

param N integer > 0;
param a {1..N};
param result {i in 1..N} = sum {j in 1..i} a[j];

and then in a data file, give AMPL data for param N and param a from the first column of your spreadsheet (as in this shortened example):

param N := 6;
param a :=
1 0
2 0.3571
3 0.35867
4 0.36026
5 0.36186
6 0.36347 ;

Then param result will contain the values from the second column of the spreadsheet.

Bob Fourer
am...@googlegroups.com

=======

Dinesh Babu Seenivasan

unread,
May 2, 2017, 4:22:36 AM5/2/17
to am...@googlegroups.com
Hi Robert,

Thanks for your information. I will try and let you know!

Regards,
Dinesh.

Reply all
Reply to author
Forward
0 new messages