Find the rth "0" in specific columns in a matrix

1 次查看(过去 30 天)
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.

采纳的回答

Andrei Bobrov
Andrei Bobrov 2017-10-27
编辑:Andrei Bobrov 2017-10-27
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
>>

更多回答(1 个)

Image Analyst
Image Analyst 2017-10-27
In general:
rows = 10;
columns = 16;
M = randi([0 1], rows,columns)
r = 2 % Whatever...
% Start and Goal Points
linearIndexes = find( M(:) == 0, r, 'first' )
[r1,c1] = ind2sub( size( M ), linearIndexes(end)) % Start Point
linearIndexes = find( M(:) == 0, r, 'last' )
[r2,c2] = ind2sub( size( M ), linearIndexes(1)) % Goal Point

标签

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by