How to find average of certain cells in a column if it's associated with another cells in another column?
4 次查看(过去 30 天)
显示 更早的评论
What if you also want to take the average of other values associated with other numbers in column 2. Let's say you have:
A = [1, 1
2, 1
3, 2
4, 2
5, 2
6, 3
7, 3];
where in column 2, I arranged the numbers in order, so column 2 has [1,1,2,2,2,3,3]. There are three unique numbers, {1,2,3}, where 1 appears 2 times; 2 appears 3 times; 3 appears 2 times.
I want to find the average of all numbers in column 1 that are associated with 1 in column 2; all numbers in column 1 associated with 2 in column 2; all numbersin column 1 associated with 3 in column 2. So I make a new array:
unique_column_2 = unique(A{:,2});
avg_column_1 = zeros(length(unique_column_2),1);
After this I'm stuck, I tried many if loops and I would get NaN for every cell in avg_column_1. I tried your synax up there and I still get NaN.
All I want is an array to compute the average of values that are associated with certain values on the other columns. Thank you so much if you can help!
0 个评论
回答(1 个)
Ameer Hamza
2020-11-23
You can use splitapply()
A = [1, 1
2, 1
3, 2
4, 2
5, 2
6, 3
7, 3];
[grps, vals] = findgroups(A(:,2));
out = [splitapply(@mean, A(:,1), grps) vals]
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!