How do I combine information from 2 arrays into a single array?
조회 수: 2 (최근 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)
댓글 수: 2
채택된 답변
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에서 MATLAB Report Generator에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!