Find index of middle 1 in a logical row

2 visualizzazioni (ultimi 30 giorni)
Abbas Husain
Abbas Husain il 17 Mar 2021
Risposto: Image Analyst il 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 Commento
John D'Errico
John D'Errico il 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.

Accedi per commentare.

Risposte (1)

Image Analyst
Image Analyst il 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

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by