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

조회 수: 1 (최근 30일)
monkey_matlab
monkey_matlab 2017년 10월 27일
편집: Andrei Bobrov 2017년 10월 27일
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

카테고리

Help CenterFile Exchange에서 Computational Geometry에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by