MATLAB Answers

Combining curves to create a single average curve

198 views (last 30 days)
Dominic Hui
Dominic Hui on 27 Oct 2016
Commented: Lasse Mausehund on 17 Jun 2019
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
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.

Sign in to comment.

Answers (2)

KSSV
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')

  2 Comments

Jan
Jan on 28 Oct 2016
This does not consider the detail "the number of and the value of X and Y differs".
KSSV
KSSV on 28 Oct 2016
Numbers can be brought to equal number using interpolation.

Sign in to comment.


Jan
Jan on 28 Oct 2016
Edited: Jan on 28 Oct 2016
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')

  1 Comment

Lasse Mausehund
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')

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!