Welcome on board.  Here I would focus on the 'overall additions'.

Given:
   a=:1 2 3 4 5
   b=:1 2

From your description you want to find the 'cartesian sum' of a over b (ie the outer product of all possible '+' combinations of a and b). I would proceed as follows ... note also that NB. lines in the following are comments):

NB. This is the 'cartesian sum' of all items of a added 'over' all items of b, hence result is an array with shape <5 2> representing the 5x2 sums.
   a+/b
2 3
3 4
4 5
5 6
6 7

NB. Now we can 'sum' up these items using +/ (note that this sums the rows, or differently expressed, 'down the columns') ...
   +/a+/b
20 25

NB. Now we can 'sum' up these (resulting) items using +/ again ...
   +/+/a+/b
45

NB. You can also use ',' to 'list' the items after the cartesian sum, meaning only one sum is then required...
   +/,a+/b
45

By thinking in terms of 'array applications/results' the loops tend to evaporate.

Hope this helps.../Rob Hodgkinson

PS: I saw Henry posted a response too just before I sent this, but thought you may still find this helpful by way of explanation.


On 04/08/2008, at 9:43 AM, Ian Gorse wrote:


I want to be able to add each of the values in 'b' with each of the values
in 'a', then sum them up


for example
(a[0]+b[0]) + (a[1]+b[0]) + (a[2]+b[0]) +(a[3]+b[0]) + (a[4]+b[0]) ) = 2
3 4 5 6 = 20
which is (1+1) +  (2+1) +  (3+1) + (4+1) + (5+1) = 20

(a[0]+b[1]) + (a[1]+b[1]) + (a[2]+b[1]) +(a[3]+b[1]) + (a[4]+b[1]) ) = 3
4 5 6 7 = 25
which is (1+2) +  (2+2) +  (3+2) + (4+2) + (5+2) = 25

total = 20 + 25 = 45


----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to