From: Emily Bauner on
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.
From: Walter Roberson on
Emily Bauner wrote:
> 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

No performances promises, but

B = cell2mat(cellfun(@(v)
[v.',repmat(0,1,max(diff(find(diff(A))+1))-length(v))],accumarray(A.',A,[],@(v)
ans ='Uniform',0));

Except of course I would break that into two lines or more.
From: Bruno Luong on
You might use this 2 tools on FEX:

http://www.mathworks.com/matlabcentral/fileexchange/24255-consecutive-vector-spliter
http://www.mathworks.com/matlabcentral/fileexchange/22909-padcat

>> A = [1 2 2 3 3 3 4 4 4 4 5 5 5 5 6 6 6 7 7 8];
>> c = SplitVec(A);
>> B = padcat(c{:})

B =

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

>> B(isnan(B)) = 0

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

% Bruno
From: Emily Bauner on
Thanks a lot, guys. I appreciate your suggestions. I actually worked
out two solutions to my problem based on your ideas and they both work
great. Thanks!
From: Emily Bauner on
Thanks so much for your suggestion, got it!


Walter Roberson <roberson(a)hushmail.com> wrote in message <mXiKn.30304$wV2.8403(a)newsfe23.iad>...
> Emily Bauner wrote:
> > 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
>
> No performances promises, but
>
> B = cell2mat(cellfun(@(v)
> [v.',repmat(0,1,max(diff(find(diff(A))+1))-length(v))],accumarray(A.',A,[],@(v)
> ans ='Uniform',0));
>
> Except of course I would break that into two lines or more.