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

조회 수: 8(최근 30일)
Tim 26 Feb 2020
댓글: Star Strider 27 Feb 2020
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 26 Feb 2020
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 27 Feb 2020
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 27 Feb 2020
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.

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

### Community Treasure Hunt

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

Start Hunting!

Translated by