What is the shortest way to make matrix from a vector using the 1-of-K coding scheme?

How to make matrix from a vector using the 1-of-K coding scheme but without a for cycle? (1,1,2,3,1,3,2) to (1,0,0; 1,0,0; 0,1,0; 0,0,1; 1,0,0; 0,0,1; 0,1,0)

 Accepted Answer

This is easy using sub2ind:
>> C = [1,1,2,3,1,3,2];
>> R = 1:numel(C);
>> A = zeros(numel(C),max(C));
>> A(sub2ind(size(A),R,C)) = 1
A =
1 0 0
1 0 0
0 1 0
0 0 1
1 0 0
0 0 1
0 1 0

More Answers (0)

Asked:

on 25 May 2015

Edited:

on 25 May 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!