How do I combine information from 2 arrays into a single array?
3 次查看(过去 30 天)
显示 更早的评论
I have two variables and minutes which look like this: hours: 1 3 4 minutes: 33 12 27
I want to combine the two so it looks like..
Time:
1.33 3.12 4.27
(the numbers change on every loop and are much longer, I have like 63 different times to combine every time I run my script)
采纳的回答
Guillaume
2017-10-12
编辑:Guillaume
2017-10-12
You would be much better off converting your hours and minutes to a duration array than your ad-hoc notation:
d = duration(hours, minutes, 0);
This is a lot more practical if you then want to calculate the time elapsed between two points, or other related time calculations.
If you really want to use your ad-hoc format:
time = hours + minutes / 100
doing calculations using this format will be a lot more complicated, particularly as some numeric values such as 1.75 are not even valid times using that notation.
更多回答(2 个)
Geoff Hayes
2017-10-12
Marissa - if you have two arrays named hours and minutes as
hours = [1 3 4];
minutes = [33 12 27];
then you can add the two as
combinedTime = hours + minutes/60;
where
combinedTime =
1.5500 3.2000 4.4500
Note that I divided the minutes array by 60 so that we get the fractional part of the hour (so 33 minutes is 0.55 of one hour).
0 个评论
Cam Salzberger
2017-10-12
Hello Marissa,
If you are looking to get a numeric result, you can simply do this:
h = [1 3 4];
m = [33 12 27];
combined = h+m./100;
That's a little weird though, since that's not really in any units you would normally use. Normally, you'd want the numeric result in terms of either hours or minutes:
combinedHours = h+m./60;
combinedMinutes = h.*60+m;
If you're looking for a bunch of character vectors in a cell array, then you could do something like this:
combined = arrayfun(@(hr, mn) sprintf('%d.%d', hr, mn), h, m, 'UniformOutput', false)
However, it's probably better to just make these into durations, and manipulate the format how you want it (if you have R2014b+):
combined = hours(h)+minutes(m);
-Cam
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!