Find index of middle 1 in a logical row
2 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
John D'Errico
2021 年 3 月 17 日
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.
回答 (1 件)
Image Analyst
2021 年 4 月 2 日
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 件のコメント
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!