Find the rth "0" in specific columns in a matrix
Show older comments
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.
Accepted Answer
More Answers (1)
Image Analyst
on 27 Oct 2017
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
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!