MATLAB: Repeat previous row if condition

repeat row

Hi, I have an nx2 matrix, the first column gives the order, 10 20 30 40 and then repeats again, but if there is no observation it jumps to the next (eg if no 40 then it has 10 20 30 10 20 30 40 ….)
What I need is to repeat what is in the previous row in the case where there is no last (40) or next to last (30):
A) If there is no 40 but there is 30, then create row 40 and repeat element of 30 in the second column.
B) If there is no 40 and no 30 but there is 20, then create row 30 and 40 and repeat element of 20 in the second column.
C) If there is no 30 but there is 20, then creaste row 30 and repeat element of 20 in the second column.
I give an example with matrix M1 below for the 3 cases above.
Original matrix M1 is 12×2
M1 = [
10 44;
20 72;
30 21;
40 13;
10 32;
20 26;
30 55;
10 23;
20 98;
10 36;
20 84;
40 22]
New matrix M2 is 16×2
M2 = [
10 44;
20 72;
30 21;
40 13;
10 32;
20 26;
30 55;
40 55;
10 23;
20 98;
30 98;
40 98;
10 36;
20 84;
30 84;
40 22]
In M2 since the first cycle 10 20 30 40 in M1 was ok no additions.
But the second cycle in M1 has no 40, so M2 creates the row 40 and repeats element of 30.
The third cycle has no 30 nor 40, but has 20, so creates 30 and 40 and repeats element of 20.
The fourth cycle has no 30 so creates 30 and repeats element of 20 (note 40 is not touched)
Help please

Best Answer

% Parameters
cycleLength = 4; % number of rows in a cycle
indexMult = 10; % multiplier for index within cycle
orders = M1(:, 1);
% get output row indexes
ind = cycleLength * (cumsum(orders == indexMult) - 1) + orders/indexMult;
% number of rows in output matrix, so that have complete cycle at end
indlast = ceil(ind(end)/cycleLength) * cycleLength;
indall = 1:indlast;
% set up output matrix and allocate adjusted indices to first column
M2 = zeros(indlast, 2);
M2(:,1) = indexMult * (mod(indall-1, cycleLength) + 1);
% put data into correct rows of second column
M2(ind, 2) = M1(:, 2);
% propagate missing data - first element in each gap
jumps = diff([ind; indlast+1]);
gappos = ind(jumps > 1);
M2(gappos+1, 2) = M2(gappos, 2);
% propagate missing data - second element in double gap
gappos = ind(jumps > 2);
M2(gappos+2, 2) = M2(gappos+1, 2);
% assume no gaps longer than 2 elements