How to evaluate mean for column

3 views (last 30 days)
I have a data with 5 columns: X,Y,Z,A,B, the first three columns represent coordinates, the next ones some attributes of objects.
A column has values: 0 or 1, B columns has values: 1, 1, 1, 2, 2, 3, 3, ,3 ,3 , 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, ....
I would like to evaluate the mean value of A column for every individual value in column B. Eg. Evaluate mean value from column A but only for points which in B have value 1.
Does somebody know which function should I use to do this? Thank you in advance!

Accepted Answer

Michael Haderlein
Michael Haderlein on 5 May 2015
You can use arrayfun:
dx=zeros(100,1);
dx(randi(100,10,1))=1;
B=cumsum(dx);
A=(1:100).^2;
meanvals=arrayfun(@(x) mean(A(B==x)),unique(B));
  9 Comments
Karolina
Karolina on 6 May 2015
Super! Thank you very much! Have a nice day!

Sign in to comment.

More Answers (2)

Andrei Bobrov
Andrei Bobrov on 6 May 2015
[~,~,c] = unique(B);
out = accumarray(c(:),A(:),[],@mean);

Ahmet Cecen
Ahmet Cecen on 5 May 2015
Below does the example you listed, change the value 1 to do the others.
mean(A(B==1))
  1 Comment
Karolina
Karolina on 5 May 2015
Thank you for your answer. Do you know if there is some way to do this for all values in my B column automatically? In my B column I have values from "1" to "n" (I do not know the biggest value) and for every value I would like to have the mean from A column.

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!