Clear Filters
Clear Filters

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

2 views (last 30 days)
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 Comment
Wlmistrzow
Wlmistrzow on 3 Nov 2019
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);

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 3 Nov 2019
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))

More Answers (1)

Thiago Henrique Gomes Lobato
Edited: Thiago Henrique Gomes Lobato on 3 Nov 2019
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 Comments
Wlmistrzow
Wlmistrzow on 3 Nov 2019
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
Edited: Thiago Henrique Gomes Lobato on 3 Nov 2019
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)

Sign in to comment.

Categories

Find more on Operators and Elementary Operations in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!