First, I have to give my standard disclaimer, that despite the commonly held notion that loops should generally be avoided in MATLAB, loops have actually become much more efficient in modern releases of MATLAB, in large part, due to the JIT accelerator. So, certainly, benchmark your code to determine if loops actually are a bottleneck.
That said, my first thought on how to approach this problem without a loop was to index into an identity matrix (as shown below).
identityMatrix = eye(max(v(:)));
result = identityMatrix(:,v);
I think that this is a nice, clean looking solution; however, I don't necessarily know that it is significantly more efficient than using a loop. As a point of comparison, I implemented the following solution using a loop:
numRows = max(v(:));
numCols = length(v);
result = zeros(numRows,numCols);
for i=1:numCols
result(v(i),i) = 1;
end
Based on my test runs, it looks like the top (no loop) solution is generally faster for those cases where v
is not very long. However, when v
contains many elements (>100 for example), I was actually seeing average times where the loop solution was beating the alternative.