Find index of middle 1 in a logical row
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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
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.
Risposte (1)
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
0 Commenti
Vedere anche
Categorie
Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!