how to find average value of floating numbers ??

4 次查看(过去 30 天)
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

采纳的回答

Sean de Wolski
Sean de Wolski 2014-3-11
编辑:Sean de Wolski 2014-3-11
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 个)

Andrei Bobrov
Andrei Bobrov 2014-3-11
编辑:Andrei Bobrov 2014-3-11
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]

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by