필터 지우기
필터 지우기

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!

답변 (1개)

Ameer Hamza
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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by