Message Boards Message Boards

0
|
2130 Views
|
7 Replies
|
0 Total Likes
View groups...
Share
Share this post:
GROUPS:

Manipulation of lists.

Posted 10 years ago

Suppose I were given a list, which contained pairs of integers. For example: {{a_1,b_1}, {a_2,b_2}, {a_3,b_3}, ...,{a_n,b_n}}

What code would I use to compute the following? : b_1/a_1 + b_2/a_2 + b_3/a_3 + ...+ b_n/a_n

7 Replies
Posted 10 years ago
x = {{a1, b1}, {a2, b2}, {a3, b3}, {an, bn}}
Total[Table[x[[i, 2]]/x[[i, 1]], {i, Length[x]}]]
POSTED BY: Jim Baldwin

Or using pure functions:

list = Table[{ToExpression["a" <> ToString[i]], ToExpression["b" <> ToString[i]]}, {i, 1, 5}]

and then

Total[#[[1]]/#[[2]] & /@ list]

Alternatively, this works:

Total[MapThread[Divide, Transpose[list]]]

Best wishes,

Marco

POSTED BY: Marco Thiel
Total[MapThread[Divide, Transpose[list]]]

for list:= {{2,2},{5,1}} outputs 12/5 rather than 6/5. Can you help me out?

Dear Anand,

no. It gives 6 as expected.

enter image description here

Cheers,

Marco

POSTED BY: Marco Thiel

My apologies, it does indeed give 6. However, I would like it to compute the following: 2/2 + 1/5 = 6/5. If I remove the Transpose[] function, then it outputs 12/5. Can you help me out? Thanks.

In that case you need to do

Total[MapThread[Divide,Transpose[Reverse /@ list]]]

Cheers,

Marco

POSTED BY: Marco Thiel

Thank you Marco!

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract