From: Jos (10584) on
Emily Bauner <emily.tting(a)gmail.com> wrote in message <4ad1b7f4-2b33-4c9b-abee-ff47df0cf603(a)e28g2000vbd.googlegroups.com>...
> Hi all,
>
> I'm looking for a fast way to distribute vector elements in a given
> matrix such that identical elements are listed in the same matrix row;
> the tricky part is that the vector has fewer elements than the matrix.
> For instance, assume that I have vector A:
>
> A = [1 2 2 3 3 3 4 4 4 4 5 5 5 5 6 6 6 7 7 8]
>
> I need some command that gives me matrix B, where B is
>
> B =
>
> 1 0 0 0
> 2 2 0 0
> 3 3 3 0
> 4 4 4 4
> 5 5 5 5
> 6 6 6 0
> 7 7 0 0
> 8 0 0 0
>
> This operation is very time-sensitive in my code as it has to be done
> often and with varying vector/matrix sizes. Therefore I would like to
> avoid a loop if at all possible.
>
> Any ideas would be greatly appreciated.

Here is another idea, vectorized and pretty quick without explicit for-loops, using a few low-level built-in ML commands:

% data
A = [1 2 2 3 1 1 1 1 2 2 6 6 6 7 7 8] ;

% engine (based on my NONES submission on the FEX)
n = diff([0 find(diff(A)~=0) numel(A)])
B = cumsum([n ; repmat(-1,max(n)-1,numel(n))])
B(B<0) = 0
B(B>0) = A
B = B.'

hth
Jos