Calculating the weighted average of a list

Dec 30, 2010 at 7:22pm

Calculating the weighted average of a list

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?

#54167
Dec 30, 2010 at 7:55pm

zl, vexpr and Peter Elsea’s Lobjects are your friends…

#194890
Dec 30, 2010 at 8:23pm

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

– Pasted Max Patch, click to expand. –
#194891
Dec 30, 2010 at 9:26pm

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

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):

– Pasted Max Patch, click to expand. –

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;

#194892
Dec 30, 2010 at 11:16pm

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:

Alex

– Pasted Max Patch, click to expand. –
#194893
Dec 30, 2010 at 11:22pm

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

#194894
Jan 2, 2011 at 2:20am

yep, sure enough, there are cleaner ways to do this! :)