Azzera filtri
Azzera filtri

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

36 visualizzazioni (ultimi 30 giorni)
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!

Risposta accettata

Voss
Voss il 25 Apr 2022
% 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 Commenti
Marcella Roth
Marcella Roth il 26 Apr 2022
Thank you so much! Is there a way to only include positive numbers in the average?
Voss
Voss il 26 Apr 2022
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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Line Plots in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by