How to find the indices of same values within a vector and bin them together

7 次查看(过去 30 天)
I have two vectors with the same length (N). For example:
A=[ 1 2 3 3 3 3 4 5]; B=[ 9 8 7 6 5 6 7 8];
What I need to do is to take an average over elements in vector 'B' that their corresponding indices in vector 'A' have same values. In this example, element 3,4,5,6 in vector A are all equal to '3' so I need to take an average over (7+6+5+6/4) in vector B. I need to do this over a large data and bin them together. I tried different ways and it didn't work. How can I do this?
  3 个评论
MatlabUser17
MatlabUser17 2018-4-24
I want to keep the other elements as well. Obviously, since the other elements have not been repeated in this example the average over one element is the same, but if they repeat I will take an average of them as well.
In summary, I need to find the same values from vector A and bin them together and take an average over their corresponding values in vector B.
let's say I have a large data:
kk=find(~isnan(B)); A=A(kk); B=B(kk); [A,IX]=sort(A); B=B(IX); u=unique(A) hist1=histc(A,u)
Up to here I have sorted the data from small to large, and have found similar values in A with their number of repetition. But I need to find their indices so I can extract them from B and take the average.

请先登录,再进行评论。

采纳的回答

Ameer Hamza
Ameer Hamza 2018-4-24
The following statement will return the list of all the averages according to the way you mentioned in your question.
meanVector = splitapply(@(x) mean(x), B', A')
since A have 5 unique elements, meanVector will also contain 5 elements corresponding to the mean value from B.
  10 个评论

请先登录,再进行评论。

更多回答(1 个)

Star Strider
Star Strider 2018-4-25
编辑:Star Strider 2018-4-25
See if this works with your data:
A=[ 1 2 3 3 3 3 4 5];
B=[ 9 8 7 6 5 6 7 8];
[Au,~,ix] = unique(A(:),'stable'); % Unique Elements & Indices (Convert To Column Vector), Keep Original Order
Ar_mean = accumarray(ix, B, [], @mean); % Means Of Single & Repeated Values
Result = [Au, Ar_mean] % Elements Of ‘A’ In Column #1, Corresponding ‘mean’ Of ‘B’ In Column #2
AB_Tbl = table(Au, Ar_mean) % Table (Optional)
Result =
1 9
2 8
3 6
4 7
5 8
AB_Tbl =
Au Ar_mean
__ _______
1 9
2 8
3 6
4 7
5 8
  2 个评论
MatlabUser17
MatlabUser17 2018-4-25
编辑:MatlabUser17 2018-4-25
Thanks, Star! it works, I got similar results from both answers. I wanted to accept both answers but seems like it's not possible. I really appreciate your help.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by