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

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

로그인 to comment.

### 채택된 답변

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 3:10
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 4:07
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.

로그인 to comment.

### 추가 답변(0개)

이 질문에 답변하려면 로그인을(를) 수행하십시오.