Averaging data in several columns within certain intervals of data

조회 수: 4 (최근 30일)
Chad Wiggins
Chad Wiggins 2015년 12월 14일
댓글: Chris Turnes 2015년 12월 14일
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)

답변 (2개)

Guillaume
Guillaume 2015년 12월 14일
편집: Guillaume 2015년 12월 14일
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
Chris Turnes
Chris Turnes 2015년 12월 14일
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)];

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


Star Strider
Star Strider 2015년 12월 14일
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.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by