Thread Subject: Means of array with class information

Subject: Means of array with class information

From: Foo Fighter

Date: 18 Sep, 2009 08:10:10

Message: 1 of 4

Hi,

I have an array of measurement data, e.g:
mmData = [ 31 4 -21 -1 -21 10 13 3 -17 8
-22 -1 -7 -10 11 ];

each datapoint belongs to a class:
mmClass = [1 3 1 2 2 2 1 2 3 2
1 3 3 3 1];

How can I get the mean of each class without using a for loop?

Thanks!
John

Subject: Means of array with class information

From: dpb

Date: 21 Sep, 2009 16:44:33

Message: 2 of 4

Foo Fighter wrote:
> Hi,
>
> I have an array of measurement data, e.g:
> mmData = [ 31 4 -21 -1 -21 10 13 3 -17 8
> -22 -1 -7 -10 11 ];
>
> each datapoint belongs to a class:
> mmClass = [1 3 1 2 2 2 1 2 3 2
> 1 3 3 3 1];
>
> How can I get the mean of each class without using a for loop?

Sometimes a for loop is the answer, even in ML...

Interesting how this question has come up (in slightly differing guises)
so frequently over last few weeks.

In a thread not too long ago somebody asked in terms of a SAS "BY"
clause. I seem to recollect maybe Bruno did a File Exchange submission
in that regard after that question???? I didn't find the thread but
eternal-september doesn't have a long retention period so it probably
already dropped off the horizon...

--

Subject: Means of array with class information

From: Nathan

Date: 21 Sep, 2009 18:23:35

Message: 3 of 4

On Sep 18, 1:10 am, Foo Fighter <foofig...@gmail.com> wrote:
> Hi,
>
> I have an array of measurement data, e.g:
> mmData = [ 31     4   -21    -1   -21    10    13     3   -17     8
> -22    -1    -7   -10    11 ];
>
> each datapoint belongs to a class:
> mmClass = [1     3     1     2     2     2     1     2     3     2
> 1     3     3     3     1];
>
> How can I get the mean of each class without using a for loop?
>
> Thanks!
> John

This isn't a for loop, but would be nicer to do as one...
classmean1 = mean(mmData(mmClass==1))
classmean2 = mean(mmData(mmClass==2))
classmean3 = mean(mmData(mmClass==3))

OR (works with any number of classes)

for i=1:max(mmClass)
classmean(i) = mean(mmData(mmClass==i))
end

So... Like dpb said: Sometimes a for loop is the answer


-Nathan

Subject: Means of array with class information

From: Bruno Luong

Date: 21 Sep, 2009 18:34:04

Message: 4 of 4

>
> So... Like dpb said: Sometimes a for loop is the answer
>

But not the only answer:

accumarray(mmClass(:), mmData, [], @mean)

Bruno

Tags for this Thread

Everyone's Tags:

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Tag Activity for This Thread
Tag Applied By Date/Time
mean Sprinceana 18 Sep, 2009 05:14:12
array Sprinceana 18 Sep, 2009 05:14:12
vector Sprinceana 18 Sep, 2009 05:14:12
rssFeed for this Thread

Contact us at files@mathworks.com