how to find average value of floating numbers ??

5 views (last 30 days)
Hello all,
I have an n-by-2 array comprised of floating numbers.
In the second column of this array, there are some arrays having same floating numbers.
I want to sort this array with respect to the second column and find the average value of the arrays having same floating numbers.
For example,
A = [0.33,0;0.53,0.2;0.433,0.2;0.11,0.5;0.95,0.4;0.99,0.5;0.32,0;0.44,0.3;0.38,0.4;0.62,0.1;0.23,0.4;0.44,0.5;0.76,0.5]
[B, I] = sort(A(:,2));
C = A(I,:)
Sorting was done successfully, and I tried to find the average of the arrays, using accumarray(subs,val). But, because ‘subs’ always requires positive integer, I can’t use this syntax in my case of accumulation of floating numbers.
Is there any solution for this? You may as well to use other syntax…
Thanks in advance

Accepted Answer

Sean de Wolski
Sean de Wolski on 11 Mar 2014
Edited: Sean de Wolski on 11 Mar 2014
Use unique to generate indices of unique floating point values
A = [0.33,0;0.53,0.2;0.433,0.2;0.11,0.5;0.95,0.4;0.99,0.5;0.32,0;0.44,0.3;0.38,0.4;0.62,0.1;0.23,0.4;0.44,0.5;0.76,0.5];
[uA,~,idxA] = unique(A(:,2)); % unique values and index
muA = accumarray(idxA,A(:,1),[],@mean); % mean of values at each index
[uA muA] % display
Also, you can use sortrows() to save yourself a step up above:
C = sortrows(A,2); %sort along second column

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 11 Mar 2014
Edited: Andrei Bobrov on 11 Mar 2014
A = [0.33,0;0.53,0.2;0.433,0.2;0.11,0.5;0.95,0.4;0.99,0.5;0.32,0;0.44,0.3;0.38,0.4;0.62,0.1;0.23,0.4;0.44,0.5;0.76,0.5]
[a,b,c] = unique(A(:,2),'first');
[~,i0] = sort(b);
[~,i1] = sort(i0);
anew = a(i0);
c1 = i1(c);
out = [accumarray(c1,A(:,1),[],@mean),anew]

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!