replace values in char array if conditions are met
5 views (last 30 days)
Show older comments
I have a datestr of 15 minute data from a certain location (minDNB):
ex) minDNB = '00','15','30','45','00','15',30','45' etc.
my goal is to replace each value or create a new matrix with fractions of an hour:
goal: newminDNB = 0.00, 0.25, 0.50, 0.75, 1.00, 1.25, 1.50, 1.75, 2.00, etc.
How should I go about this? I would like to loop through minDNB because some time stamps are missing and I need to retain gaps in the data. Thanks.
time00 = '00';
time25 = '15';
time50 = '30';
time75 = '45';
A = size(minDNB)
for i = 1:numel(minDNB)
if minDNB(i) == time00
A(i) = 0.00;
else if minDNB == time25
A(i) = 0.25 ;
else if minDNB(i) == time50
A(i) = 0.50 ;
else if minDNB(i) == time75
A(i) = 0.75 ;
end
end
end
end
end
0 Comments
Accepted Answer
Dave B
on 3 Nov 2021
Edited: Dave B
on 3 Nov 2021
I think your input is a cell array of character vectors:
minDNB={'00','15','30','45','00','15', '30','45'}
and you want the output to be doubles, could you just do:
str2double(minDNB)/60
Or a fun alternative:
hours(minutes(str2double(minDNB)))
4 Comments
Dave B
on 3 Nov 2021
Edited: Dave B
on 3 Nov 2021
This is pretty similar to @Stephen's answer below but with a modification because your data are one big char and not a cell array of chars. I used double(string( for this but you could allso use str2double(cellstr(. And also I changed the < to a <= note this caveat:
if you're missing 1 or 2 consecutive measurements it's fine, if you want to increment the hour when you're missing 3 measurements (i.e. '00' '15' '30' '30' '45') then < should be <=, and if you're missing 4 measurements it's of course indistinguishable from just being the next hour!
mins=double(string(minDNB));
hrs = mins/60;
hrs=cumsum([0;diff(hrs)<0])+hrs;
But note: if you started with timeDNB, there's a way more natural path:
dt=datetime(timeDNB); % convert to datetime
hrs2=hours(dt-dt(1)); % or alternatively: [0;cumsum(hours(diff(dt)))]
This catches that you're missing measurements on March 11th (I think?)
More Answers (1)
Stephen23
on 3 Nov 2021
C = {'00','15','30','45','00','15','30','45'};
V = str2double(C)/60;
V = V+cumsum([0,diff(V)<0])
3 Comments
See Also
Categories
Find more on Dates and Time 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!