Another approach is through bsxfun
and unique
. Assuming that A
is a row vector, you would do the following:
un = unique(A.', 'stable');
out = bsxfun(@times, bsxfun(@eq, A, un), un);
out
contains your desired result. This code deserves some explanation. The first line of code determines all unique entries in A
stored in un
, but provides them in stable
order, or in the order in which they are encountered. Not doing this would also sort the values too. I figure that the case of values from 1 to 4 is a simplified example and you’d want to do this for numbers in any arbitrary order and them appearing anywhere in the vector as well.
The second line of code is actually quite elegant. Let’s start with the first bsxfun
call that’s nested inside:
bsxfun(@eq, A, un)
bsxfun
is a very nice function that broadcasts over singleton dimensions. What this means for our case is that A
is a row vector and un
is a column vector, and this would produce a matrix where we find the element-wise equality of two matrices – one matrix which duplicates row vectors of A
for as many elements as we have in un
and another matrix which duplicates column vectors for as many elements as there are in A
. The result of this is a matrix where each row tells you which locations in A
matched a particular value in un
starting from the beginning of un
(first row) to the end of un
(last row). The last part of this is to take this equality matrix and do an element-wise multiplication with un
using another bsxfun
call so that un
broadcasts itself again column-wise like what was done in bsxfun(@eq, A, un)
. The result would be to zero out the exact locations for each row that did not equal to the corresponding value in un
that is represented and we thus have our result.
Example
>> A = [1 1 1 1 1 2 2 2 3 3 3 4 4 4]
A =
Columns 1 through 13
1 1 1 1 1 2 2 2 3 3 3 4 4
Column 14
4
Calling the above code gives us:
>> out
out =
Columns 1 through 13
1 1 1 1 1 0 0 0 0 0 0 0 0
0 0 0 0 0 2 2 2 0 0 0 0 0
0 0 0 0 0 0 0 0 3 3 3 0 0
0 0 0 0 0 0 0 0 0 0 0 4 4
Column 14
0
0
0
4
3
solved Given a row vector, how do I create an indicator matrix placing each value in its respective column location?