# How to take an average from range of values?

2 views (last 30 days)
Haya Ali on 17 Mar 2023
Commented: Dyuman Joshi on 17 Mar 2023
I have this array and according to excel histogram plot the mostly values are located in the range [-0.5,0.5]. I want to sort all values from the array A that lies in this range and take there average. How can I do this? A= [0.0000 0.4341 -0.0000 -0.5910 -0.0352 2.0350 -0.0000 -0.9597 0.0000 -1.2164 -2.7826 -0.0000 0.3716 -0.0000 -0.0000 -0.0000 1.4557 0.0000 -0.0000 0.5599 -0.0000 -0.2463 -0.7001 0.0000]

Dyuman Joshi on 17 Mar 2023
It seems you have copied the data from Excel and there is a loss of data in doing that.
A= [0.0000 0.4341 -0.0000 -0.5910 -0.0352 2.0350 -0.0000 -0.9597 0.0000 -1.2164 -2.7826 -0.0000 0.3716 -0.0000 -0.0000 -0.0000 1.4557 0.0000 -0.0000 0.5599 -0.0000 -0.2463 -0.7001 0.0000];
%range
idx = A>=-0.5 & A<=0.5;
%sorted A values in the range
B = sort(A(idx))
B = 1×16
-0.2463 -0.0352 0 0 0 0 0 0 0 0 0 0 0 0 0.3716 0.4341
avg = mean(B)
avg = 0.0328
Note that the range containing maximum number of elements can vary according to the bin size and the start point.
For example -
%bin size 0.5, start point -3.5, the range [0 0.5] has the max no. of elements
bin=-3.5:0.5:3.5;
histogram(A,bin)
xticks(bin) %bin size - 0.3, start point -3.2, range with max elements is [-0.2 0.1]
bin=-3.2:0.3:3;
histogram(A,bin)
xticks(bin) ##### 2 CommentsShow 1 older commentHide 1 older comment
Dyuman Joshi on 17 Mar 2023
It will depend upon the size and the starting point of the range, as I said above.
Let's say the bin size is 0.5, and the starting and end points are -3 and 3 respectively
A = [0.0000 0.4341 -0.0000 -0.5910 -0.0352 2.0350 -0.0000 -0.9597 0.0000 -1.2164 -2.7826 -0.0000 0.3716 -0.0000 -0.0000 -0.0000 1.4557 0.0000 -0.0000 0.5599 -0.0000 -0.2463 -0.7001 0.0000];
bin = -3:0.5:3;
h = histogram(A, bin);
xticks(bin) %index of the maximum value
[~,idx] = max(h.Values)
idx = 7
%Range with maximum number of elements
bin(idx:idx+1)
ans = 1×2
0 0.5000
The range can be verified from the histrogram as well.