Can i find 'mean' of on column , based on second column ?

2 次查看(过去 30 天)
I have random matrix A 120x6. In last column I have only values 1 or 2. I want to find the min, max, median, and mean of first column for this rows, where in 6 column is 1.
6 8 2 9 5 2
1 8 6 10 5 2
1 10 2 7 2 1
3 3 2 7 2 1
2 10 8 3 1 1
2 1 4 6 4 1
10 9 2 2 9 2
3 8 5 2 5 1
4 3 9 8 6 2
4 8 4 7 7 2
10 1 4 9 7 2
  1 个评论
Wlmistrzow
Wlmistrzow 2019-11-3
i tryied with this
for i=1:120
if A(i,6)==1
d = mean(mean(A(:,1)));
e = median(A(:,1));
end
end
disp(d);

请先登录,再进行评论。

采纳的回答

Image Analyst
Image Analyst 2019-11-3
Try this:
m = [...
6 8 2 9 5 2
1 8 6 10 5 2
1 10 2 7 2 1
3 3 2 7 2 1
2 10 8 3 1 1
2 1 4 6 4 1
10 9 2 2 9 2
3 8 5 2 5 1
4 3 9 8 6 2
4 8 4 7 7 2
10 1 4 9 7 2]
col6Is1 = m(:, 6) == 1
minOfColumn1 = min(m(col6Is1, 1))
maxOfColumn1 = max(m(col6Is1, 1))
medianOfColumn1 = median(m(col6Is1, 1))
meanOfColumn1 = mean(m(col6Is1, 1))

更多回答(1 个)

Thiago Henrique Gomes Lobato
编辑:Thiago Henrique Gomes Lobato 2019-11-3
You can first find the index where columm 6 is one, save it in a vector and then use it as a mask for your first columm, in this way you also vectorize your code, which runs faster in Matlab :
A = rand(120,6)*2;
A(:,6) = ceil(A(:,6)); % Values here can be only either 1 or 2
IndexToTakeAverageAndEtc = find(A(:,6)==1); % Find all rows where A(:,6)==1
Mean = mean(A(IndexToTakeAverageAndEtc,1)); % Take the mean only for the rows where the last columm is 1
Max = max(A(IndexToTakeAverageAndEtc,1));
...
  2 个评论
Wlmistrzow
Wlmistrzow 2019-11-3
6 8 2 9 5 2
1 8 6 10 5 2
1 10 2 7 2 1
3 3 2 7 2 1
2 10 8 3 1 1
2 1 4 6 4 1
10 9 2 2 9 2
3 8 5 2 5 1
4 3 9 8 6 2
4 8 4 7 7 2
10 1 4 9 7 2
i must to have mean from values from column 1 where in the same row , but i the 6 column is number 1. in this example i must to have mean from (1 ,3 ,2,2,3).
Thiago Henrique Gomes Lobato
编辑:Thiago Henrique Gomes Lobato 2019-11-3
Sorry, I made a typo in my initial code in getting the value from the frist columm, just change the 6 for a 1 (I also edited the answer), this give the result that you want:
A = [6 8 2 9 5 2
1 8 6 10 5 2
1 10 2 7 2 1
3 3 2 7 2 1
2 10 8 3 1 1
2 1 4 6 4 1
10 9 2 2 9 2
3 8 5 2 5 1
4 3 9 8 6 2
4 8 4 7 7 2
10 1 4 9 7 2];
A(:,6) = ceil(A(:,6)); % Values here can be only either 1 or 2
IndexToTakeAverageAndEtc = find(A(:,6)==1); % Find all rows where A(:,6)==1
Mean = mean(A(IndexToTakeAverageAndEtc,1)) % Take the mean only for the rows where the last columm is 1
...
Mean =
2.2000
Which is the mean for (1 ,3 ,2,2,3)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Operators and Elementary Operations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by