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

조회 수: 1 (최근 30일)
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
Voss 2022년 2월 4일
% 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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by