keep repeated x values and average y values

Dear all
I have the following data:
x=[4.1 2.7 3.2 2.5 4.1 2.5 0 5 6.1 2.5];
y=[10 16 11 24 8 18 20 7 6 4];
I would like to take repeated values only once that mean x should become:
xn=
0
2.5
2.7
3.2
4.1
5.
6.1
the correspodnig values of y should be the average:
yn=
20
15.33333333
16
11
9
7
6
that means 4.1 is rpeated twice: x(1)=4.1 x(5)=4.1
and thus the corresponding y data are: y(1)=10 y(5)=8
in this case only one 4.1 value is keept but y should be averaged: (10+8)/2 = 9
your helps are highly appreciated.
cheers

답변 (1개)

Nade Sritanyaratana
Nade Sritanyaratana 2014년 8월 6일

0 개 추천

You may want to consider using accumarray .
The following code uses unique to find all unique values of x and also an inverse mapping ix from the unique array to the original array index. It then uses accumarray to average all y data that has matching ix:
x=[4.1 2.7 3.2 2.5 4.1 2.5 0 5 6.1 2.5];
y=[10 16 11 24 8 18 20 7 6 4];
[xn, ~, ix] = unique(x)
yn = accumarray(ix,y,[],@mean)

댓글 수: 4

Adam
Adam 2014년 8월 6일
Hi ,
Thanks for the quick reply. it does not work!
the line:
yn=accumarray(ix,y,[],@mean)
gives the following error:
Error using ==> accumarray Second input VAL must be a vector with one element for each row in SUBS, or a scalar.
cheers
Hi,
I don't get this error just by running the exact lines I provided, but it sounds like for some reason ix and y do not have the same number of elements in your environment. Try looking at the size of both arrays:
>> size(y)
>> size(ix)
Adam
Adam 2014년 8월 7일
Hi,
this eamaple is not working:
x=[4.1 2.7 3.2 2.5 4.1 2.5 0 5 6.1 2.5];
y=[10 16 11 24 8 18 20 7 6 4];
[xn, ~, ix] = unique(x)
cheers yn = accumarray(ix,y,[],@mean)
ix and y in this example have the same size i.e. 10
I am not getting the same error using MATLAB R2014a. It's possible that one or more of the functions (unique, accumarray, or mean) are being shadowed. You can check this by running "which -all {function_name}" on the command window.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Operators and Elementary Operations에 대해 자세히 알아보기

질문:

2014년 8월 6일

댓글:

2014년 8월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by