Sum values on the maximum number of consecutive days
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
KSSV
2023-6-26
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 个评论
Image Analyst
2023-6-26
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!