how to find average value of floating numbers ??

4 vues (au cours des 30 derniers jours)
Lee
Lee le 11 Mar 2014
Commenté : Lee le 11 Mar 2014
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

Réponse acceptée

Sean de Wolski
Sean de Wolski le 11 Mar 2014
Modifié(e) : Sean de Wolski le 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
  1 commentaire
Lee
Lee le 11 Mar 2014
This is exactly what I want!
Thanks~~

Connectez-vous pour commenter.

Plus de réponses (1)

Andrei Bobrov
Andrei Bobrov le 11 Mar 2014
Modifié(e) : Andrei Bobrov le 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]

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by