How to average within bins? Indexing again...

조회 수: 5 (최근 30일)
B.M.
B.M. 2014년 2월 14일
답변: Jos (10584) 2014년 2월 14일
I am trying to average data corresponding to bins. Here is a simplified example (attached). I have real distances in the first column, and then real durations. I have binned the distances and added them to the array (with the help of Matlab Central users). Now what I want to do is extract the durations that match a given bin (say, 0), and then average them. Each bin will then be associated, in a different array, with its average duration.
Here's what I have so far, but I don't want to have to rewrite all of these statements for each bin. I have >35 bins! I'm not good with indexing but sometimes it seems there are easier ways to do things than with indexing, so hopefully that is the case here.
=======================
%%%%%%%%%%starting array
dist=[2 4 6 9];
duration=[3 4 10 11];
bin=[0 0 5 5];
data=[dist' duration' bin']
%%%%%%%%%%extracts durations only where bin=some number
bin0=logical(data(:,3)==0);
bin0dur=(data(:,2).*bin0);
bin5=logical(data(:,3)==5);
bin5dur=(data(:,2).*bin5);
%%%%%%%%%%removes zeros
bin0dur(bin0dur==0)=[];
bin5dur(bin5dur==0)=[];
%%%%%%%%%%takes mean of remaining durations
meandur0=mean(bin0dur);
meandur5=mean(bin5dur);
%%%%%%%%%%puts mean durations with their bins
bins=[0 5];
durs=[meandur0 meandur5];
datafinal=[bins' durs']

답변 (2개)

Jos (10584)
Jos (10584) 2014년 2월 14일
Using ACCUMARRAY to average the values belonging to the same bin:
dist = [2 4 6 9] ;
duration = [3 4 10 11];
bin = [0 0 5 5] ; % how did you get those?
[BinValue,~,ix] = unique(bin) ;
AvgDuration = accumarray(ix,duration,@mean) ;
Result = [BinValue AvgDuration]
Extra: You can use histc to bin the distances
DistEdges = [0 5 10]
[n, bin] = histc(dist, DistEdges)

per isakson
per isakson 2014년 2월 14일
편집: per isakson 2014년 2월 14일
I think it is accumarray, Construct array with accumulation you are looking for. The online help includes some examples.
  댓글 수: 3
per isakson
per isakson 2014년 2월 14일
Wouldn't it be feasible to create subs?
B.M.
B.M. 2014년 2월 14일
I don't know what you mean--but ended up taking a different approach since I needed to pull out data for multiple conditions. Thanks for your suggestion!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by