Effacer les filtres
Effacer les filtres

How to average within bins? Indexing again...

6 vues (au cours des 30 derniers jours)
B.M.
B.M. le 14 Fév 2014
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']

Réponses (2)

Jos (10584)
Jos (10584) le 14 Fév 2014
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 le 14 Fév 2014
Modifié(e) : per isakson le 14 Fév 2014
I think it is accumarray, Construct array with accumulation you are looking for. The online help includes some examples.
  3 commentaires
per isakson
per isakson le 14 Fév 2014
Wouldn't it be feasible to create subs?
B.M.
B.M. le 14 Fév 2014
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!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by