How to average within bins? Indexing again...

4 ビュー (過去 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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by