MATLAB Answers


How to evaluate mean for column

Asked by Karolina on 5 May 2015
Latest activity Commented on by Karolina on 6 May 2015
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!


Sign in to comment.

3 Answers

Answer by Michael Haderlein on 5 May 2015
 Accepted Answer

You can use arrayfun:
meanvals=arrayfun(@(x) mean(A(B==x)),unique(B));


Thanks I will read the info for unique function.
I will try to explain my second part in other way. In my B column I would like to select only these values which are appearing more than 5 times (that is why I am using histc). Next I would like to check the evaluated mean (from A column) for these values which are appearing more than 5 times. In the mean column I want to select threshold=1.3, which will divide my data for two parts. At the end I would like to create a new column with values: 1, 2 which will represent my data divided using my threshold.
small=nums>5 & out<1.3;
large=nums>5 & out>=1.3;
In sl you should have what you want. Plese see that I used "nums" as variable name as "Size" is pretty close to "size" and that's a Matlab function. Better don't name variables like this to prevent errors from the beginning.
Super! Thank you very much! Have a nice day!

Sign in to comment.

Answer by Andrei Bobrov
on 6 May 2015

[~,~,c] = unique(B);
out = accumarray(c(:),A(:),[],@mean);


Sign in to comment.

Answer by Ahmet Cecen on 5 May 2015

Below does the example you listed, change the value 1 to do the others.

  1 Comment

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.