Asked by Mirlan Karimov
on 10 Apr 2019

array = [ 1 2 3 4 5 6 ];

find(array == 3);

This is clear!

I want to find fractional index when array == 2.5 or any other intermediate value.

Answer by Stephen Cobeldick
on 11 Apr 2019

Edited by Stephen Cobeldick
on 11 Apr 2019

Accepted Answer

Much simpler (and also works for multiple val values):

interp1(array,1:numel(array),val)

For example:

>> array = [2,4,5,7,8,9]; % a more interesting sequence.

>> val = 3.8;

>> interp1(array,1:numel(array),val)

ans = 1.9

And compared to the (very complex) accepted answer:

>> idxAboveVal = find( array >= val, 1 );

>> idxFract = idxAboveVal - ( array( idxAboveVal ) - val ) / ( array( idxAboveVal ) - array( idxAboveVal - 1 ) )

idxFract = 1.9

Note: this answer is based on the original answer by madhan ravi:

Answer by Adam
on 10 Apr 2019

Edited by Adam
on 10 Apr 2019

val = 2.5;

idxAboveVal = find( array >= val, 1 );

idxFract = idxAboveVal - ( array( idxAboveVal ) - val ) / ( array( idxAboveVal ) - array( idxAboveVal - 1 ) );

I'm guessing this is what you mean.

Obviously it would need error checking if idxAboveVal is 1 or empty.

There's probably neater ways to do it too, or shorter, at least!

Mirlan Karimov
on 10 Apr 2019

Adam
on 11 Apr 2019

The find function simply finds integer indices into an array that correspond to the logical expression you give it. It isn't magic. It can't find things that don't exist. Hence I used it to find the next value greater than the one you want and did the required maths from there.

You should always give an example that shows the full complexity of the question you are asking though if you want a useful answer.

Giving what people call a 'Minimum working example' is fine, but it needs to have the full complexity of what you actually want to know still, otherwise it's of no use.

A manual approach to things causes bugs if you get it wrong, not if you get it right.

Mirlan Karimov
on 11 Apr 2019

I had a manual code but then realized yours is shorter and I will be using that one. Thanks!

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## Stephen Cobeldick (view profile)

Direct link to this comment:https://de.mathworks.com/matlabcentral/answers/455509-find-the-index-of-given-value-in-an-array#comment_692300

## madhan ravi (view profile)

Direct link to this comment:https://de.mathworks.com/matlabcentral/answers/455509-find-the-index-of-given-value-in-an-array#comment_692308

Sign in to comment.