How do I combine information from 2 arrays into a single array?

2 visualizzazioni (ultimi 30 giorni)
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)

Risposta accettata

Guillaume
Guillaume il 12 Ott 2017
Modificato: Guillaume il 12 Ott 2017
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.

Più risposte (2)

Geoff Hayes
Geoff Hayes il 12 Ott 2017
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).

Cam Salzberger
Cam Salzberger il 12 Ott 2017
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

Categorie

Scopri di più su MATLAB Report Generator in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by