time format as hr:min:sec

sir, i have three columns- one containing hour, next minute , third on sec.
hr=[10,10,10,10];
min=[00,00,01,01];
sec=[00,30,00,30];
i need a single column of time as
[10:00:00,10:00:30,10:01:00,10:01:30]
what is the method?

 Accepted Answer

hr=[10,10,10,10];
min=[00,00,01,01];
sec=[00,30,00,30] ;
iwant = [] ;
for i = 1:length(hr)
str = sprintf('%02d:%02d:%02d\n',hr(i),min(i),sec(i)) ;
iwant = [iwant ; str] ;
end
iwant

8 Comments

thank you sir
See my answer for a much more efficient solution (no loop, no expanding array inside loop, just one sprintf call).
sir actually my matrix is having 21028 elements.this code works upto1404 elements and then terminating showing the comment _Dimensions of matrices being concatenated are not consistent._also can this be written in excel file?
@seema niran: This solution suffers from the iterative growing of the output array. This is not a syntax error and does not cause the error you observe. But it slows doen the processingmassively, when the input gets larger.
Please post the value of the 1405.th input and the complete error message. Try Stephen's suggestion.
my hr started with 10,reaches 23 and then from 0-15. min ranges from 0-59 and sec 0 and 30. this is the 706th term.(16:38:00).the error message is
*Error using vertcat
Dimensions of matrices being concatenated are not consistent.
Error in timeconversion(line 13) iwant = [iwant ; str] ;*
@seema: Why do you post the 706th element, when the code works up to the 1404th element?
Please use the debugger. Type this in the command window:
dbstop if error
and run the code again. Now Matlab stops, when the error occurres and you can check the value of str. Perhaps a number is negative or NaN? We cannot guess this.
sir, it is correct. the 707th term in data was a negetive one making all the problem. thanks
@seema niran: note that my Answer works with negative values as well, without error, as well as being simpler and much more efficient that the answer you accepted.

Sign in to comment.

More Answers (2)

Stephen23
Stephen23 on 23 Jan 2017
Edited: Stephen23 on 23 Jan 2017
>> hr=[10,10,10,10];
>> min=[00,00,01,01];
>> sec=[00,30,00,30];
>> fprintf('%02d:%02d:%02d\n',[hr;min;sec])
10:00:00
10:00:30
10:01:00
Or to put it into a string or cell array:
>> S = sprintf('%02d:%02d:%02d\n',[hr;min;sec])
S =
10:00:00
10:00:30
10:01:00
>> C = strsplit(strtrim(S),'\n')'
C =
'10:00:00'
'10:00:30'
'10:01:00'
'10:01:30'
All the previous answers assume you want text, and that may be what you want. But if you're using R2014b or later, you can use durations:
>> hr=[10,10,10,10];
>> min=[00,00,01,01];
>> sec=[00,30,00,30];
>> d = duration(hr,min,sec)
d =
10:00:00 10:00:30 10:01:00 10:01:30

Categories

Asked:

on 23 Jan 2017

Answered:

on 6 Feb 2017

Community Treasure Hunt

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

Start Hunting!