How to make a table of strings from a table of numerics

2 views (last 30 days)
I want to apply convert_hour function to everyrow but it does some weird stuff that I don't understand
arr = [1;2;3;4];
T = array2table(arr);
convert_hour(T.arr)
function out = convert_hour(hour)
left = floor(hour/60);
right = floor(mod(hour, 60));
if left < 10; left = sprintf("0%d", left); else; left = sprintf("%d", left); end
if right < 10; right = sprintf("0%d", right); else; right = sprintf("%d", right); end
out = sprintf("%s:%s\n", left, right);
end
--------- the output is this
ans =
"00000000:01020304"

Accepted Answer

Star Strider
Star Strider on 15 May 2022
I’m not certain what you want, however substituting compose for sprintf may be appropriate —
arr = [1;2;3;4];
T = array2table(arr);
convert_hour(T.arr)
ans = 4×1 string array
"00:01" "00:02" "00:03" "00:04"
function out = convert_hour(hour)
left = floor(hour/60);
right = floor(mod(hour, 60));
if left < 10; left = compose("0%d", left); else; left = compose("%d", left); end
if right < 10; right = compose("0%d", right); else; right = compose("%d", right); end
out = compose("%s:%s", left, right);
end
.
  4 Comments
Steven Lord
Steven Lord on 15 May 2022
If this isn't homework, I'd just convert it to a duration.
numHours = randperm(8760, 10)
numHours = 1×10
4625 7125 2836 3691 4086 360 8208 1551 4714 66
d = hours(numHours)
d = 1×10 duration array
4625 hr 7125 hr 2836 hr 3691 hr 4086 hr 360 hr 8208 hr 1551 hr 4714 hr 66 hr
d.Format = 'hh:mm'
d = 1×10 duration array
4625:00 7125:00 2836:00 3691:00 4086:00 360:00 8208:00 1551:00 4714:00 66:00
or if you want to subtract off days and just give hours and minutes after midnight:
h = rem(d, hours(24))
h = 1×10 duration array
17:00 21:00 04:00 19:00 06:00 00:00 00:00 15:00 10:00 18:00
Cavit Ertugrul Sirt
Cavit Ertugrul Sirt on 15 May 2022
Thank you, but, can't I just make this into a function since I need to do this 3 times in my code.

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!