Effacer les filtres
Effacer les filtres

Averaging data in several columns within certain intervals of data

6 vues (au cours des 30 derniers jours)
Chad Wiggins
Chad Wiggins le 14 Déc 2015
Commenté : Chris Turnes le 14 Déc 2015
I have a sets of very large data (in the form of a numeric matrix) in which I'm trying to just get some averages, and I think a for-loop may be the easiest way to do this but I'm not exactly sure how to do it. Column 2 is a distance traveled from 0 to 20km. Column 3 gives me some data one a subjects power output on a cycle ergometer during that travel, and column 4 gives me a subjects Heart Rate. What I would like to do is get an average of columns 3 and 4 for each km traveled (final matrix would display 20 rows with 3 colums, column 1 being distance in integers of 1 through 20, column 2 being the mean power output on the cycle, and column 3 being the mean heart rate during that kilometer)

Réponses (2)

Guillaume
Guillaume le 14 Déc 2015
Modifié(e) : Guillaume le 14 Déc 2015
Assuming you have a fairly recent version of matlab (2015a or newer), what you want to do is very easy: use discretize to distribute your distances into integral bins, and accumarray to compute your average:
demodata = [zeros(100, 1), linspace(0, 20, 100)', rand(100, 2)];
bins = [0:20]';
binidx = discretize(demodata(:, 2), bins);
meanpower = accumarray(binidx, demodata(:, 3), [20 1], @mean);
meanheartrate = accumarray(binidx, demodata(:, 4), [20 1], @mean);
out = [bins, meanpower, meanheartrate]
  1 commentaire
Chris Turnes
Chris Turnes le 14 Déc 2015
If you have R2015b, you can condense a little further by using splitapply:
demodata = [zeros(100, 1), linspace(0, 20, 100)', rand(100, 2)];
bins = [0:20]';
binidx = discretize(demodata(:, 2), bins);
out = [bins, splitapply(@mean, demodata(:, 3:4), binidx)];

Connectez-vous pour commenter.


Star Strider
Star Strider le 14 Déc 2015
If you have the same number of measurements in each kilometer, it would be easiest to use the reshape function once on each of columns 3 and 4:
Ts = 0.1; % Sampling Time (Every 0.1 km)
dist = 0:Ts:20-Ts; % Create Data
HR = randi([60 180], size(dist,2), 1);
PW = randi([10 20], size(dist,2), 1);
Data = [nan(size(PW,1),1) dist' PW HR]; % Create Data Matrix
PWmean = mean(reshape(Data(:,3), (1/Ts), []));
HRmean = mean(reshape(Data(:,4), (1/Ts), []));
Result = [[1:20]; PWmean; HRmean]';
If you don’t have regular sampling times and the same number of measurements per kilometer, then this code will not work. You will have to use find to locate the beginning and end of each kilometer, and a loop to do the calculations on the irregular length data vectors.

Catégories

En savoir plus sur Creating and Concatenating Matrices 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