I had a very similar question, so I did not want to open a new one. I wanted to convert an index row vector into a matrix with units in the rows (instead of columns) of indices. I could use the previous answer and invert it, but I thought this would work better with very large matrices.
octave> x = [2 1 3 1]; octave> m = setRowsToOne(x, 3) m = 0 1 0 1 1 0 0 0 0 0 1 0
I could not figure out how to use sub2ind to accomplish this, so I figured it out myself.
function matrixResult = setRowsToOne(indexOfRows, minimumNumberOfRows) numRows = max([indexOfRows minimumNumberOfRows]); numCols = columns(indexOfRows); matrixResult = zeros(numRows, numCols); assert(indexOfRows > 0, 'Indices must be positive.'); matrixResult(([0:numCols-1]) * numRows + indexOfRows) = 1; end x = [2 1 3 1]; m = setRowsToOne(x, 3)
source share