Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand matrix based on first row value (MATLAB)

My input is the following:

X = [1 1; 1 2; 1 3; 1 4; 2 5; 1 6; 2 7; 1 8];

X =

 1     1
 1     2
 1     3
 1     4
 2     5
 1     6
 2     7
 1     8

I am looking to output a new matrix based on the value of the first column. If the value is equal to 1 -- the output will remain the same, when the value is equal to 2 then I would like to output two of the values contained in the second row. Like this:

 Y =

     1
     2
     3
     4
     5
     5
     6
     7
     7
     8

Where 5 is output two times because the value in the first column is 2 and the same for 7

like image 970
Geoff Avatar asked Feb 20 '26 14:02

Geoff


1 Answers

Here it is (vectorized):

C = cumsum(X(:,1))
A(C) = X(:,2)
D = hankel(A)
D(D==0) = inf
Y = min(D)

Edit:

Had a small bug, now it works.

like image 63
Bitwise Avatar answered Feb 22 '26 03:02

Bitwise