Tak
Tak

Reputation: 3616

Get relative middle index from the non-zeros values of a vector

I have a vector that starts with zeros then some positive values then again zeros. I want to get the index of the cell located in the middle of the non-zero values. For example, if A=[0;0;0;2;2;3;5;7;0;0] then the index of the middle cell will be 3 which has the value 3.

Upvotes: 2

Views: 84

Answers (1)

Divakar
Divakar

Reputation: 221584

Assuming you have just one set of non-zeros values in A, you can use two approaches here.

Approach 1 -

relative_middle_index = round(numel(nonzeros(A))/2)

Approach 2 -

relative_middle_index = round(diff(find(diff(A~=0)))/2)

You can get the absolute middle indices using two approaches.

Approach 1 -

absolute_middle_index = round((find(A~=0,1) + find(A~=0,1,'last'))/2)

Approach 2 -

absolute_middle_index =  round(mean(find(diff(A~=0)))) 

Upvotes: 4

Related Questions