How to find the index of the center element in a 2d array if all the elements are the same?

조회 수: 14 (최근 30일)
I'm attempting to find the index of the center element to be used later on.
I have a 5x5 array of -1's created with the following code.
x = -1*ones(5,5)
I'm able to find the index of the center element if the center element differs from the other elements using find (x == value).

채택된 답변

Star Strider
Star Strider 2020년 2월 26일
If all the elements are the same, one approach is:
x = -1*ones(5,5);
[r,c] = ind2sub(size(x), ceil(numel(x)/2))
Thsi will only work on matrices with odd numbers of elements.
  댓글 수: 2
Tim
Tim 2020년 2월 27일
Thanks for the response. That wasn't exactly what I was looking for but your response helped me arrive at what I was looking for. The approach I used to find the linear index is:
x = -1*ones(5,5);
indx = sub2ind(size(x),ceil(length(x)/2),ceil(length(x)/2))
indx =
13
Star Strider
Star Strider 2020년 2월 27일
As always, my pleasure!
The linear index is actually just:
indx = ceil(numel(x)/2);
I wasn’t certain which one you wanted, so I opted for the subscripts as the desired result.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by