Forums > MaxMSP

Calculating the weighted average of a list

Dec 30 2010 | 7:22 pm

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?

Dec 30 2010 | 7:55 pm

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

Dec 30 2010 | 8:23 pm

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. --

Dec 30 2010 | 9:26 pm

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;

Dec 30 2010 | 11:16 pm

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:


-- Pasted Max Patch, click to expand. --

Dec 30 2010 | 11:22 pm

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

Jan 02 2011 | 2:20 am

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

Viewing 7 posts - 1 through 7 (of 7 total)

Forums > MaxMSP