Combining curves to create a single average curve
Show older comments
Hi, I've got some data from an experiment that has been repeated three times. I'd like to plot the average of the curves. However, for each replicate the number of and the value of X and Y differs. I was wondering what the best approach is for dealing with this? I've tried to interpolate by using a common x scale but run into difficulties was the number of Y vallues differ.
I'm very new to matlab and anyhelp would be greatly appreciated!
Thanks
1 Comment
Jan
on 28 Oct 2016
If you post what you have tried, suggesting an improvement would be much easier and more likely to match your current code.
Answers (2)
Interpolation is the correct approach:
% Test data:
x1 = linspace(0, 2*pi, 100);
y1 = sin(x1) + rand(size(x1)) * 0.2 + 0.1;
x2 = linspace(0, 2*pi, 110);
y2 = sin(x2) + rand(size(x2)) * 0.2;
x3 = linspace(0, 2*pi, 120);
y3 = sin(x3) + rand(size(x3)) * 0.2 - 0.1;
% Interpolate to get same time resolution:
x = linspace(0, 2*pi, 200);
yy1 = interp1(x1, y1, x);
yy2 = interp1(x2, y2, x);
yy3 = interp1(x3, y3, x);
y = mean([yy1; yy2; yy3], 1);
axes('NextPlot', 'add'); % as: hold on
plot(x1, y1, 'r', x2, y2, 'g', x3, y3, 'b', x, y, 'k')
3 Comments
Lasse Mausehund
on 17 Jun 2019
Thanks a lot for the answer Jan!
One thing a stumbled across is that the interpolated graph (yy1) slightly varies from the original one. I figured out that if you increase the number of interpolated points drastically, accuracy increases. Can you explain why that is the case? Should you not expect the exact same graph if you would use the same number of samples?
% Test data:
x1 = linspace(0, 2*pi, 100);
y1 = sin(x1) + rand(size(x1)) * 0.2 + 0.1;
% Interpolate to get same time resolution:
x = linspace(0, 2*pi, 200);
yy1 = interp1(x1, y1, x);
x2 = linspace(0, 2*pi, 500);
yy5 = interp1(x1, y1, x2);
axes('NextPlot', 'add'); % as: hold on
plot(x1, y1, 'r')
plot(x, yy1, 'b')
plot(x2, yy5, 'g')
Khaoula Ouazzani
on 28 Mar 2023
@Jan thank you for the information (eventhough I read it years later lol).
I have anoter question: what if my data has got different xi (I can't interpolate relatively to one X)?
Jan
on 13 Apr 2023
@Khaoula Ouazzani: Can you give an explicit example?
KSSV
on 28 Oct 2016
clc; clear all ;
t = linspace(0,2*pi) ;
x1 = 0.1*sin(t) ;
x2 = 0.15*sin(t) ;
x3 = 0.2*sin(t) ;
%
hold on
plot(t,x1,'r') ;
plot(t,x2,'b') ;
plot(t,x3,'g') ;
%%calculate average
xavg = (x1+x2+x3)/3 ;
plot(t,xavg,'k')
Categories
Find more on Interpolation 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!