MATLAB: Find the rth “0” in specific columns in a matrix

MATLAB

Hello,
In the code below, thanks to the solution by Cedric Wannaz posted here , I am able to efficiently find the first and last "0" in an n x m matrix.
n = 10;
m = 20;
M = randi([0 1], n,m);
%%Start and Goal Points
[r1,c1] = ind2sub( size( M ), find( M(:) == 0, 1, 'first' )); % Start Point
[r2,c2] = ind2sub( size( M ), find( M(:) == 0, 1, 'last' )); % Goal Point
How do I go about finding the 3rd or 4th or the rth "0" in any column. For example, how to find the index of the 3rd "0" in the 6th column?
Thanks.

Best Answer

cols = [1 3 4 6 7]; % selected columns.

num_zeros = [3,4];% The ordinal number "0" in each selected column.

M_nozeros = cumsum(~M).*~M;
[~,ii] = ismember(M_nozeros(:,cols),num_zeros);
[k,jj] = ndgrid(1:size(M,1),cols);
idx = [k(:),jj(:)];
out = accumarray(ii(:) + 1,1:numel(ii),[],@(x){idx(x,:)});
out = out(2:end);
out - cell array, here each cell corresponds to the ordinal number "0" ( num_zeros), each cell contains a double matrix: rows are the ordinal number of the row containing zero, the columns correspond to cols.
Use:
>> cols = [1 3 4 6 7]; % selected columns.
num_zeros = [3,4];% The ordinal number "0" in each selected column.
M = rand(15,10) < .25
M =
15×10 logical array
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 1 0 0 1
1 0 0 1 1 0 0 0 0 1
0 0 0 1 0 0 1 0 0 0
0 0 0 0 1 0 0 0 0 0
0 0 0 1 1 0 0 0 0 0
0 1 0 0 0 1 0 0 0 0
0 1 0 0 0 0 0 0 1 1
1 0 1 0 0 1 0 0 0 0
0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 1 0 0 0
0 0 0 1 1 1 1 1 0 1
0 0 0 0 0 0 1 0 0 0
0 0 1 0 0 1 1 0 0 0
1 0 0 0 0 0 1 0 0 0
>>
>> M_nozeros = cumsum(~M).*~M;
[~,ii] = ismember(M_nozeros(:,cols),num_zeros);
[k,jj] = ndgrid(1:size(M,1),cols);
idx = [k(:),jj(:)];
out = accumarray(ii(:) + 1,1:numel(ii),[],@(x){idx(x,:)});
out = out(2:end);
>>
>> out{:}
ans =
4 1
3 3
3 6
5 4
5 7
ans =
4 6
5 1
6 7
4 3
7 4
>>