function rowsWithProperty = findLastTwoOccurrenes(M) % Initialise rowsWithProperty to a 2x1 vector rowsWithProperty = zeros(2,1); % Method: Scan from the last row and up % If a row if the property is found % - Increase numRowsFound (= a number to keep track of the number of rows % with the property; initially set to 0) % - Increase indexForRowsWithProperty (= an index to store row numbers % found in the answer rowsWithProperty; initially set to 1) % % row is the row number to be checked. It's initialised to the number of % rows in the matrix M. Decrease by 1 each time a row has been checked. numRowsFound = 0; indexForRowsWithProperty = 1; row = size(M,1); % Iterate as long has 2 rows with the property has not been found and there % are still rows to check while (numRowsFound < 2) & (row >= 1) % Can use & or && if isPropertySatisfied(M(row,:)) % a row with the property has been found rowsWithProperty(indexForRowsWithProperty) = row; indexForRowsWithProperty = indexForRowsWithProperty + 1; numRowsFound = numRowsFound + 1; end row = row - 1; end % Remove zero entries in rowsWithProprty if row == 0 rowsWithProperty = rowsWithProperty(1:numRowsFound); end % Alternative Method: % rowsWithProperty(rowsWithProperty == 0) = [];