MATLAB: Matrix Indices Problem

arrayfindindexingMATLABmatrix

Given a matrix e.g. A = [0 1 2 0 0; 0 3 4 5 0; 6 7 8 9 10; 0 0 0 11 0]
what MATLAB code will generate a vector of the column numbers of the first non-zero element in each row?
For this example the vector returned should be: [2;2;1;4]

Best Answer

[junk, idx] = max(logical(A),[],2)
idx will be you index vector.