Averaging data in several columns within certain intervals of data
4 次查看(过去 30 天)
显示 更早的评论
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)
0 个评论
回答(2 个)
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
2015-12-14
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
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!