MATLAB: How to split numeric values and store them

datafor loopMATLABtime

I have the array below with activities 1, 2 and 3 and the times the system has spent in these activities. Not every row is a new date. For example, the first value (24) is 1/1/2015, however, the two following values (22.3 + 1.7 = 24) is on 1/2/2015, and so on.
Modes2 =
0 0 24.0000
0 0 22.3000
0 0 1.7000
0 0 13.0000
0 11.0000 0
0 24.0000 0
0 24.0000 0
0 24.0000 0
0 24.0000 0
0 17.2833 0
0 3.7667 0
2.9500 0 0
7.1167 0 0
16.8833 0 0
24.0000 0 0
To further analyse these, the need to be stored per 6 hours in something like the following.
Time_periods1 =
1/1/2015 6 hr 0 0 0
1/1/2015 12 hr 0 0 0
1/1/2015 18 hr 0 0 0
1/1/2015 24 hr 0 0 0
1/2/2015 6 hr 0 0 0
1/2/2015 12 hr 0 0 0
1/2/2015 18 hr 0 0 0
1/2/2015 24 hr 0 0 0
1/3/2015 6 hr 0 0 0
1/3/2015 12 hr 0 0 0
1/3/2015 18 hr 0 0 0
1/3/2015 24 hr 0 0 0
1/4/2015 6 hr 0 0 0
1/4/2015 12 hr 0 0 0
I wrote the following, does not work, now I'm lost.
for i=1:size(Modes2,1)
for j=1:size(Time_periods2,1)
for k=1:7
if (Modes2(i,k)>0 && Modes2(i,k)<=6)
Time_periods2(j,k)=Modes2(i,k);
elseif (Modes2(i,k)>6 && Modes2(i,k)<=12)
Time_periods2(j+1,k)=Modes2(i,k)-6;
Time_periods2(j,k)=6;
elseif (Modes2(i,k)>12 && Modes2(i,k)<=18)
Time_periods2(j+2,k)=Modes2(i,k)-12;
Time_periods2(j+1,k)=6;
Time_periods2(j,k)=6;I
elseif (Modes2(i,k)>18 && Modes2(i,k)<=24)
Time_periods2(j+3,k)=Modes2(i,k)-18;
Time_periods2(j+2,k)=6;
Time_periods2(j+1,k)=6;
Time_periods2(j,k)=6;
end
end
end
end
Any ideas?

Best Answer

The code below should do the trick. You will also notice there are much more comments explaining what the code is attempting to do.
Modes2 =[
0 0 24.0000
0 0 22.3000
0 0 1.7000
0 0 13.0000
0 11.0000 0
0 24.0000 0
0 24.0000 0
0 24.0000 0
0 24.0000 0
0 17.2833 0
0 3.7667 0
2.9500 0 0
7.1167 0 0
16.8833 0 0
24.0000 0 0];
len=6;%set the boundary so we can change it later if needed
in=Modes2;%make a copy so we can change the data
out=zeros(ceil(sum(in(:))/len),size(in,2));%pre-allocate the output
ind_out=1;%start at row 1
for ind_in=1:size(in,1)
while sum(in(ind_in,:))>0
ExtractAtMost=len-sum(out(ind_out,:));
tmp=min(ExtractAtMost,in(ind_in,:));
%this min() operation works element by element, so it relies on
%every row having only 1 non-zero element
%store to output
out(ind_out,:)=tmp+out(ind_out,:);
%reduce input to prepare for next iteration
in(ind_in,:)=in(ind_in,:)-tmp;
if len-sum(out(ind_out,:)) <= 2*eps
%test if output row is already full, if so, go to next row
ind_out=ind_out+1;
end
end
end