简体   繁体   中英

Find mean values in for-loop over distributed range

I have a data like below:

49.6    46.1
49.65   46.3
50.1    47.03
50.2    47.06
51.35   46.027
51.36   46.20

I want to find the mean values of both column based on specific range of first column. for example in range of [49-50) I should calculate the mean values of the first column and mean of corresponding values in the second column. In this example the sub-array (first column only) with numbers

49.6    
49.65   

will be in range of [49-50) so I want to find the mean value for them and the mean value of the corresponding values in the 2nd column.

The range would be like 49:1:100 . The code below doesn't work properly.

for i=49:1:100
    meanWithinRange(i) = mean(data(i,1));
end

I think you are looking for logical indexing.

First, create a logical array for the in-range values of column 1:

A=[49.6    46.1
   49.65   46.3
   50.1    47.03
   50.2    47.06
   51.35   46.027
   51.36   46.20];

I = A(:,1)>=49 & A(:,1)<50;

I is a logical column vector, and is true for the rows that are in range. You can use this to index the rows you want:

>> A(I,:)
ans =
   49.6000   46.1000
   49.6500   46.3000

So now you can simply compute the mean of this result:

>> mean(A(I,:))
ans =
   49.6250   46.2000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM