how to find the column number of first zero element of each row
41 views (last 30 days)
More Answers (2)
Adam on 19 Feb 2016
Edited: Adam on 19 Feb 2016
sum( abs( cumprod( yourMatrix, 2 ) ) > 0, 2 ) + 1;
should work I think. I tested in on a small matrix I made and it seems to give the correct answer. There may be simpler methods though!
The logic behind it is as follows:
- cumprod is the cumulative product, run along each row (dimension 2) which will always be 0 for values after the first 0, hence the result of this will be a matrix in which only the elements before the first 0 on a row will be non-zero.
- abs will ensure that all non-zero elements are positive in order for the following check to work correctly.
- taking the sum of all the elements greater than 0 will give you the index of the last non-zero element.
- Adding 1 at the end will give the element of the first 0 which should always be the column immediately after the last non-zero.
If need be you can use a small tolerance e.g. 1e-6 to hard set elements below that absolute tolerance to 0 before doing this as values that are not precisely 0 will likely cause problems.