How to find the average of y over a range of x?

36 次查看(过去 30 天)
Hi Everyone,
I have a dataset containing two variables, x (time) and y (amplitude). I want to find the average amplitude over a given time range. I'm very much a beginner with MatLab and any help would be appreciated!

采纳的回答

Voss
Voss 2022-4-25
% some times, x:
x = 0:0.01:9
x = 1×901
0 0.0100 0.0200 0.0300 0.0400 0.0500 0.0600 0.0700 0.0800 0.0900 0.1000 0.1100 0.1200 0.1300 0.1400 0.1500 0.1600 0.1700 0.1800 0.1900 0.2000 0.2100 0.2200 0.2300 0.2400 0.2500 0.2600 0.2700 0.2800 0.2900
% some amplitudes, y:
y = sin(x)
y = 1×901
0 0.0100 0.0200 0.0300 0.0400 0.0500 0.0600 0.0699 0.0799 0.0899 0.0998 0.1098 0.1197 0.1296 0.1395 0.1494 0.1593 0.1692 0.1790 0.1889 0.1987 0.2085 0.2182 0.2280 0.2377 0.2474 0.2571 0.2667 0.2764 0.2860
% plot y vs x to visualize (see plot below):
plot(x,y)
% a time range, x_min and x_max:
x_min = 2.2;
x_max = 2.9;
% find the average value of y, where x is within the interval [x_min,x_max]:
y_avg = mean(y(x >= x_min & x <= x_max))
y_avg = 0.5460
% plot that too:
hold on
plot([x_min x_max],[y_avg y_avg])
  2 个评论
Marcella Roth
Marcella Roth 2022-4-26
Thank you so much! Is there a way to only include positive numbers in the average?
Voss
Voss 2022-4-26
You're welcome!
Yes, this will average just the positive numbers within the given range:
% some times, x:
x = 0:0.01:9;
% some amplitudes, y:
y = sin(x);
% a time range, x_min and x_max:
% (pick a range that includes some non-positive y values)
x_min = 2;
x_max = 6;
% find the average value of y, where x is within the interval [x_min,x_max]
% and y is positive:
y_avg = mean(y(x >= x_min & x <= x_max & y > 0))
y_avg = 0.5117

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Line Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by