Plotting mean of values based on number in column

I have a matrix [1,2,3,4,5,6; 1,2,1,2,1,2] I want to plot the mean of the values in row one based off of the values in row two i.e. the mean of 1,3,5 (because they correspond to the 1's in the second row) and the mean of 2,4,6 (because they correspond to the 2's in the second row).
The data I am actually working with is a 2X1000 matrix and has 5 different values in the second row but I want to use this example to simplify it so I can learn how to do it.
Maybe using an If loop? Or some other way of having Matlab go through the second row and store the contents of the first row into a separate matrix based off of some parameters?
I'm very new to Matlab, so the more detailed the explanation, the better.
Thank you!

 채택된 답변

Image Analyst
Image Analyst 2013년 7월 10일

0 개 추천

Hopefully this should be straightforward and easy to follow and understand.
m = [1,2,3,4,5,6; 1,2,1,2,1,2];
% Extract out the individual rows
row1 = m(1, :)
row2 = m(2, :)
% Find out how many unique numbers
% (classes, categories) there are in row2.
classes = unique(row2)
% Loop over those numbers one at a time
% finding the mean for each of them taken from row1.
for k = 1 : length(classes)
% Get the number of this class.
thisClass = classes(k)
% Find indexes in row2 with this class.
indexes = row2 == thisClass
% Get the mean of those locations in row1.
theMean(k) = mean(row1(indexes))
end
I'm sure without any comments and using some arcane MATLAB function(s) you could probably do it all in one line, and I'm sure someone will show that to you.

댓글 수: 2

Pati
Pati 2013년 7월 10일
This is great! Thank you!
Pati
Pati 2013년 7월 10일
One quick question: in regards to the "for k = 1 : length(classes)", what does the semicolon signify?

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2013년 7월 10일
편집: Andrei Bobrov 2013년 7월 10일

0 개 추천

m = [1,2,3,4,5,6; 1,2,1,2,1,2];
means = accumarray(m(2,:).',m(1,:),[],@mean);

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2013년 7월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by