# Average number of y for y=f(x) where there are several y values for the same x

1 view (last 30 days)
Saeid on 4 Feb 2022
Answered: Voss on 4 Feb 2022
I have an array y where y is a function of x but for every x there are multiple values of y.
x=[x1 x1 x1 x1 x1 x2 x2 x2 x2 x3 x3 x3 x3 x3 ...]
y=[y1 y2 y3 y4 y5 y6 ... yn]
How can I separate the values of y related to each unique x and e.g. calculate their average (or maximum or minimum) to have an array of unique x and y elements at the end that would look like this:
x=[x1 x2 x3 ... xn]
y=[mean(y1:y5) mean(y6:y9) mean(y10:y14)...]

Voss on 4 Feb 2022
% creating some x and y to replicate your situation, as I understand it:
x = repelem([1 2 3 4],1,5);
y = randn(size(x))+repelem(2:2:8,1,5);
disp(x); disp(y);
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 2.0493 1.9038 2.2196 0.8905 1.6911 5.0208 3.4631 5.1964 3.8335 4.7127 5.7153 5.3221 7.5308 5.2093 4.9359 9.5675 8.4060 7.6161 7.4658 8.1718
% Perform the requested task, as I understand it:
[ux,~,jj] = unique(x);
nux = numel(ux);
uy = zeros(1,nux);
for ii = 1:nux
uy(ii) = mean(y(jj == ii));
end
disp(ux); disp(uy);
1 2 3 4 1.7509 4.4453 5.7427 8.2455

### Categories

Find more on Matrices and Arrays in Help Center and File Exchange

R2021b

### Community Treasure Hunt

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

Start Hunting!
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}