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!

 Accepted Answer

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 Comments

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

Sign in to comment.

More Answers (1)

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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!