Calculating the weighted average of a list

agargara's icon

Hello, I'm a max newbie, and I feel like I'm making this problem a lot more complicated than it should be. I've gone through the tutorials on list processing, but I'm still having trouble making progress on this problem.

Given a list (or collection) of the following format:
1 256 0.1
2 128 0.05
3 56 0.03
4 433 0.7

I'd like to calculate a weighted average of the first parameters, using the second parameters as the weights. In other words, I want to take the following steps:
1. Find the reciprocal of the sum of all the second parameters.
2. Multiply each second parameter by this reciprocal.
3. Multiply each first parameter by its corresponding second parameter.
4. Find the mean of the weighted first parameters.

However, I'm already stuck on step 1! I'm not sure how to sum up only the second parameters. Is there an easy way of doing this?

Roald Baudoux's icon

zl, vexpr and Peter Elsea's Lobjects are your friends...

seejayjames's icon
Max Patch
Copy patch and select New From Clipboard in Max.

this is probably way too many objects for doing this. Interested to see other people's takes on it...

agargara's icon

Thanks Roald, I've been taking a look at Lobjects, and there's enough useful stuff there to make my head spin!

Max Patch
Copy patch and select New From Clipboard in Max.

seejayjames, that helps me a lot, even if it does use a lot of objects! The only problem is that I made a mistake in my description: in step 4, you don't need to compute the average, because the numbers are already weighted. You just need to sum them. So here's the slightly modified version of your patch I came up with (I also modified it to work with coll):

I'm pretty new to this, so let me know if I unknowingly introduced any bugs!

Edit: Here's my original test data formatted to paste into coll:
1, 256 0.1;
2, 128 0.05;
3, 56 0.03;
4, 433 0.7;

AlexHarker's icon

I haven't tested this much, but this should work with a few less objects (gives the same results with the supplied data). You just need to populate the coll and bang the button:

Max Patch
Copy patch and select New From Clipboard in Max.

Alex

Roman Thilenius's icon

unpack 0. 0.
expr $f1*($f2/accumulated sum of all $f2)/number of inputs

seejayjames's icon

yep, sure enough, there are cleaner ways to do this! :)
best thing about the Forum...