Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Average value of rows with certain columns

Subject: Average value of rows with certain columns

From: Murat

Date: 4 Apr, 2013 21:47:14

Message: 1 of 5

Hello everybody,

I have a huge matrix (size 1048766 x 2) and I would like to get average values of particular rows which have identical column values such as:

B=

2 45
3 45
4 45
5 50
3 50

desired result:
res=

3 45
4 50

Columns are already sorted in ascending order.

I am new to MATLAB and unfortunately I couldn't find any efficient solution to this problem. Any help would be really appreciated, thank you very much for your time!

Subject: Average value of rows with certain columns

From: dpb

Date: 5 Apr, 2013 01:57:14

Message: 2 of 5

On 4/4/2013 4:47 PM, Murat wrote:
...

> I have a huge matrix (size 1048766 x 2) and I would like to get average
> values of particular rows which have identical column values such as:
>
> B=
>
> 2 45
> 3 45
> 4 45
> 5 50
> 3 50
>
> desired result:
> res=
>
> 3 45
> 4 50
>
...

Dead ahead...

u=unique(B(:,2));
a=zeros(length(u),2);
for i=1:length(u)
   a(i)=mean(B(B(:,2)==u(i),:));
end

I haven't thought about vectorizing...

--

Subject: Average value of rows with certain columns

From: Teja Muppirala

Date: 5 Apr, 2013 05:56:05

Message: 3 of 5

A vectorized method:

B = [2 45;
       3 45;
       4 45;
       5 50;
      3 50];

[u,loc,ind] = unique(B(:,2));
TheAnswer = [u accumarray(ind,B(:,1),[],@sum)./histc(ind,1:ind(end))]

Subject: Average value of rows with certain columns

From: Bruno Luong

Date: 5 Apr, 2013 06:04:06

Message: 4 of 5

B= [2 45
3 45
4 45
5 50
3 50]

[u, ~, J] = unique(B(:,2));
[accumarray(J, B(:,1))./accumarray(J,1) u]
% or
[accumarray(J, B(:,1),[],@mean) u]

% Bruno

Subject: Average value of rows with certain columns

From: Murat

Date: 5 Apr, 2013 21:01:12

Message: 5 of 5

"Bruno Luong" <b.luong@fogale.findmycountry> wrote in message <kjlpgl$qq9$1@newscl01ah.mathworks.com>...
> B= [2 45
> 3 45
> 4 45
> 5 50
> 3 50]
>
> [u, ~, J] = unique(B(:,2));
> [accumarray(J, B(:,1))./accumarray(J,1) u]
> % or
> [accumarray(J, B(:,1),[],@mean) u]
>
> % Bruno

Thank you very much the answers, that solved my problem ...

Tags for this Thread

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.

Contact us