Sum values on the maximum number of consecutive days
2 views (last 30 days)
Show older comments
Dear all,
I want to accomplish the following:
- I have a variable (R_3) with the daily data for 1 year (matrix size is 366 rows, 1 column).
- Implement a condition of daily data > 1.
- For the days that satisfy (2), get the maximum number of consecutive days and the corresponding row number.
- Sum the values according to the row number.
- In R_3, the maximum number of consecutive days is 6 days and this would be rows 106 to 111. I want to sum the values in rows 106 to 111.
I have attached my code below. I have trouble with steps 3 & 4 and do not know how to proceed.
clear; clc;
load('Sample.mat');
a1 = find(R_3 > 1); % Condition R_3 > 1
a2 = diff(a1);
a3 = diff([0; find(diff(a2)); numel(a2)]);
a4 = max(a3)+1; % Max number of consecutive days
0 Comments
Answers (2)
KSSV
on 26 Jun 2023
load Sample.mat ;
R_3 = R_3' ;
n = 1:length(R_3) ;
ii = zeros(size(R_3));
jj = R_3 > 1 ;
ii(strfind([0,jj(:)'],[0 1])) = 1;
idx = cumsum(ii).*jj;
out = accumarray( idx(jj)',R_3(jj)',[],@(x){x'}); % gives the values seperated in cell
out_ind = accumarray( idx(jj)',n(jj)',[],@(x){x'}); % gives the indices seperated in cell
0 Comments
Image Analyst
on 26 Jun 2023
Try this (requires the Image Processing Toolbox);
% I have a variable (R_3) with the daily data for 1 year (matrix size is 366 rows, 1 column).
load('Sample.mat');
% Implement a condition of daily data > 1.
a1 = R_3 > 1; % Condition R_3 > 1
% For the days that satisfy (2), get the maximum number of consecutive days and the corresponding row number.
props = regionprops(a1, 'Area', 'PixelIdxList')
allLengths = [props.Area];
[maxLength, index] = max(allLengths)
% Sum the values according to the row number.
% In R_3, the maximum number of consecutive days is 6 days and this would be rows 106 to 111.
indexes = props(index).PixelIdxList
% I want to sum the values in rows 106 to 111.
theSum = sum(R_3(indexes))
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!