replace values in char array if conditions are met

5 ビュー (過去 30 日間)
Nicholas Modar
Nicholas Modar 2021 年 11 月 3 日
コメント済み: Dave B 2021 年 11 月 4 日
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

採用された回答

Dave B
Dave B 2021 年 11 月 3 日
編集済み: Dave B 2021 年 11 月 3 日
I think your input is a cell array of character vectors:
minDNB={'00','15','30','45','00','15', '30','45'}
minDNB = 1×8 cell array
{'00'} {'15'} {'30'} {'45'} {'00'} {'15'} {'30'} {'45'}
and you want the output to be doubles, could you just do:
str2double(minDNB)/60
ans = 1×8
0 0.2500 0.5000 0.7500 0 0.2500 0.5000 0.7500
Or a fun alternative:
hours(minutes(str2double(minDNB)))
ans = 1×8
0 0.2500 0.5000 0.7500 0 0.2500 0.5000 0.7500
  4 件のコメント
Dave B
Dave B 2021 年 11 月 3 日
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?)

サインインしてコメントする。

その他の回答 (1 件)

Stephen
Stephen 2021 年 11 月 3 日
C = {'00','15','30','45','00','15','30','45'};
V = str2double(C)/60;
V = V+cumsum([0,diff(V)<0])
V = 1×8
0 0.2500 0.5000 0.7500 1.0000 1.2500 1.5000 1.7500
  3 件のコメント
Dave B
Dave B 2021 年 11 月 4 日
if you're just going through cellstrs to get from datetime to double, you can skip that step:
d=datetime(2010,1,1,10,30,00);
d.Hour
ans = 10
d.Minute
ans = 30

サインインしてコメントする。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by