How to calculate the slope of select data points across entire dataset?
26 次查看(过去 30 天)
显示 更早的评论
Hoping I can get this point across. I'm looking to calculate the slope of certain data.
I have a dataset containing 16,725 measurements across 1994 days. Each measurement begins when the header (column 1) reads 21, but the length varies each day. For my variable of interest (column 2), I'm looking to calculate the slope under certain conditions. For example, in the first measurement period (1:9), I am interested in the slope before there is considerable change (increase) in the data (this would be points 1:5). For the second measurements period (10:20), this would be points 1:4.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/408695/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/408700/image.jpeg)
I'm not sure how I would go about doing this. I thought to incorporate diff() somehow to analyze the difference between two points, and find what values to calculate the slope for. I'm also curious if it would be difficult to do given the current formatting of the data, or if I could create a loop, restarting/recalculating everytime column 1 reads 21. As I mentioned, there are 1994 days of data, so ideally, in the end, I would have a slope value for my data of interest, 1994 points long (1 each day).
0 个评论
采纳的回答
the cyclist
2020-11-10
编辑:the cyclist
2020-11-10
Here is a straightforward method. I commented the code, so I hope you can follow the algorithm
I didn't see how you wanted to calculate the slope, so I leave that to you.
% Made up some pretend data
data = [
21 5;
20 4;
20 3;
20 2;
20 3;
20 4;
21 5;
20 4;
20 3;
20 4;
20 3;
21 5;
20 6;
20 3;
20 2;
20 3;
]
% Define where each interval starts and ends, based on location of 21
intervalStart = find(data(:,1)==21);
intervalEnd = [intervalStart(2:end)-1; size(data,1)];
% Number of intervals
numberIntervals = numel(intervalStart);
% Preallocate memory for the slope results
slope = zeros(numberIntervals,1);
% Loop over the intervals
for ni = 1:numberIntervals
% Find the end of the segment (within this interval), based on increase in data value
segmentEnd = find(diff(data(intervalStart(1):intervalEnd(1),2)) > 0,1);
% Extract the data segment
dataForSlopeCalc = data(intervalStart:(intervalStart+segmentEnd-1),2);
% Calculate the slope --- FILL THIS IN WITH YOUR DEFINITION OF THE SLOPE
%%% slope(ni) = ??????
end
1 个评论
the cyclist
2020-11-10
Per your comment via email, I edited this code so that dataForSlopeCalc does not include the element with the uptick. (I had gone back & forth on the best way to code it, and ended up uploading a mistaken "in-between" version.)
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!