Find index of middle 1 in a logical row

2 views (last 30 days)
Abbas Husain
Abbas Husain on 17 Mar 2021
Answered: Image Analyst on 2 Apr 2021
I have A = [ 0 0 0 1 1 1 0 0 0]
I'm trying to get as an output the index of the middle nonzero 1 entry - in this case: 5.
Thank you :)
  1 Comment
John D'Errico
John D'Errico on 17 Mar 2021
Confusing question. Are you just trying to find the index of the middle element? Simple:
n = numel(A);
middleind = ceil(n/2);
Of course, if you have an even number of elements, the middle index is ambiguous.
Do you know there are elements SOMEWHERE ROUGHLY in the middle, and you want to find the index of the middle of those leements that are 1? Again, what if there are an even number of unit elements?
What happens if there is more than one group of unit elements?
Until you explain/understand what you really need to do, in all circumstances, you cannot solve a problem.

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 2 Apr 2021
You can use regionprops:
A = [ 0 0 0 1 1 1 0 0 0 1 1 1 1 0] % Two regions
props = regionprops(logical(A), 'Centroid')
xy = vertcat(props.Centroid)
centroidIndexes = xy(:, 1)
for this example, you'll get two centroids:
centroidIndexes =
5
11.5

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!