MATLAB: Use conditions on a matrix and manipulate the results

conditions on matricesMATLABmatrix manipulation

Hello,
I have a matrix:
a = [1 1 1 1; 0.99 1 1 1; 0.98 0.99 1 1; 0.97 0.99 0.99 0.99]
I would like to obtain the following result:
b = [0 0 0 0; 2 0 0 0; 0 3 0 0; 0 0 4 4]
It means that at the first time when 1 changes to 0.99 look up which row is it and write it in the 'b' matrix at the same place. If this condition is not true, write zero.
Thank you!

Best Answer

This works:
a = [1 1 1 1; 0.99 1 1 1; 0.98 0.99 1 1; 0.97 0.99 0.99 0.99];
q1 = a(1:end-1,:) - a(2:end,:); % Subtract Rows From Offset Rows
q2 = a(2:end,:)==0.99; % Find Offset Rows = 0.99
q3 = [zeros(1,size(a,2)); q1 & q2]; % Create Logical Matrix (Cond 1 & Cond 2)
b = bsxfun(@times, q3, [1:size(a,1)]'); % Use ‘bsxfun’ To Number The Row Entries