Replacing cells in a cell array/Dealing with AM and PM using datenum

7 ビュー (過去 30 日間)
Kendra Wright
Kendra Wright 2014 年 11 月 24 日
コメント済み: Star Strider 2014 年 11 月 24 日
I'm creating a time stamp by converting my time and date using datenum(). Now I have the issue of the AM and PM. My thought was to run the cell array through for loop, testing to see if the string matches "PM." Which returns a 1 if true and 0 if false. Then say if it is equal to 1, force that cell in the array to equal 12, if not then equal to 0. I have a large data set right now which is made of cell arrays called Data and the third cell array is the AM and PM part. This is my code right now:
for i=1:l3
tf = strcmp(Data{1,3}{i,1},'AM')
if tf == 1
Data{1,3}{i,1} = 0;
else if tf == 1
Data{3,i}{i,1} = 12
end
end
end
It runs through the loop and tests the strings correctly but I've made an error with rewriting that array because it isn't actually changing the array. It just returns the original with the AM and PM. I want it to have either 0 or 12.

採用された回答

Star Strider
Star Strider 2014 年 11 月 24 日
The datenum function can take care of the AM and PM conversions automatically if you tell it to:
DS = ['11/24/2014 9:30 AM'; '11/24/2014 9:30 PM'];
DN = datenum(DS, 'mm/dd/yyyy HH:MM AM');
DV = datevec(DN);
See formatIn under ‘Input Arguments’ for details.
  2 件のコメント
Kendra Wright
Kendra Wright 2014 年 11 月 24 日
I felt like this was an option but I just couldn't find that in the documentation. Thanks
Star Strider
Star Strider 2014 年 11 月 24 日
My pleasure!

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

その他の回答 (1 件)

Andrew Reibold
Andrew Reibold 2014 年 11 月 24 日
編集済み: Andrew Reibold 2014 年 11 月 24 日
I'm really confused as to why you have Data{1,3}{i,1} for the first assignment, and Data{3,i}{i,1} for the second one. Shouldn't these both be the same? Could this be your issue?
Also, maybe try entering your numbers as STRINGS. Use the parenthesis.
Also, you can put strcmp directly into the if statement if that helps you clean stuff up.
Here is an example. You may need to tune it up.
for i=1:l3
if strcmp(Data{1,3}{i,1},'AM')
Data{1,3}{i,1} = '0';
else if strcmp(Data{1,3}{i,1},'PM')
Data{1,3}{i,1} = '12'
end

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by