How can I average points with just the same x-coordinate?

31 views (last 30 days)
I have many plots on top of each other, and there are a lot of points with the same x coordinate. I want to average all points same x coordinate, and plot this as one new point, so to get an idea of the general trend. Is there an easy way to do this in MATLAB?

Answers (2)

Sean de Wolski
Sean de Wolski on 20 Aug 2014
Sure!
% Sample x y
x = randi(10,100,1);
y = rand(100,1);
% Unique x's and their locations
[ux,~,idx] = unique(x);
% Accumulate
ymean = accumarray(idx,y,[],@mean);
% Plot
plot(ux,ymean)

Joseph Cheng
Joseph Cheng on 20 Aug 2014
if you have more than 1 plot as in >>plot(x,y) but more of >>plot(x1,y1,x2,y2) etc or a held plot then you can try this.
x1=1:1:20; y1=1:1:20;
x2=1:2:20; y2=1:2:20;
x3=1:3:20; y3=1:3:20;
x4=1:4:20; y4=1:4:20;
%pre-allocate average y matrix
Y = zeros(max([length(x1) length(x2) length(x3) length(x4)]),4);
Y(:,1) = y1;
[a b] = ismember(x1,x2);
Y(a,2) = y2;
[a b] = ismember(x1,x3);
Y(a,3) = y3;
[a b] = ismember(x1,x4);
Y(a,4) = y4;
av_Y = sum(Y,2)./sum(Y~=0,2);
  1 Comment
Joseph Cheng
Joseph Cheng on 20 Aug 2014
thinking about it more y could have zeros so swap out the corresponding lines
Y = nan(max([length(x1) length(x2) length(x3) length(x4)]),4);
av_Y = nanmean(Y,2)

Sign in to comment.

Categories

Find more on Line Plots 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!