MATLAB: Access every nth occurrence of a value in a matrix

matrixoccurrence

Hello. I have a matrix with '0' and '1', of variable size. For example:
A =
0 0 0 0 0
0 1 0 0 0
0 1 1 0 0
0 0 1 0 0
0 0 1 0 0
0 0 1 1 0
0 0 0 1 0
0 1 1 0 0
0 0 0 1 0
0 0 0 1 1
My goal is to create B where every '1' is changed to '0', except for every nth '1' (let's assume 3rd, for this example). The code should sweep row by row, searching from left to right.
B =
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 1
Thank you.

Best Answer

One approach:
Atv = reshape(A', [], 1); % Transpose & Reshape To Column Vector
lidx = find(Atv); % Find ‘1’ Positions
B = zeros(size(A))'; % Create Transpose Of ‘B’
B(lidx(1:3:end)) = 1; % Set Appropriate Elements To ‘1’
B = B' % Transpose To Get Desired Result