MATLAB: Change values of matrix with indices determined by a vectors values.

matrixmatrix manipulation

Assume I have some vector T of size M x 1, T is increasing containing positive intergers. Now I want to construct a Matrix b of size M x max(T) such that the m’th (m <= M) row of b has ones on columns 1 to T(m), every other element should be 0.
An example of what I seek obtained is the result of:
T = [1,2,4]';
b = zeros(size(T,1),max(T));
for m=1:size(T,1))
b(m,1:T(m))=1;
end
This is of course trivial to make using a loop (as above), but I’m looking for an elegant one-swoop method (hopefully faster).

Best Answer

Similar questions have been asked before and the prevailing finding has been that nothing is faster for this than a loop. However, a "one-swoop" method is as follows,
b=bsxfun(@le, 1:max(T), T)