MATLAB Answers

## How to pick next value from vectors?

Asked by Teemu

### Teemu (view profile)

on 4 Mar 2013
Accepted Answer by Jos (10584)

### Jos (10584) (view profile)

I have a cumulative vector, size is about 200. I want to pick up that index where value is 0,5 or value which is next to it. For example (0.1, 0.23, 0.42, 0.49, 0.52, 0.56,...), so i want to pick up index which corresponding to value 0.52. How can I do it?

Jan Simon

### Jan Simon (view profile)

on 4 Mar 2013

Does "next" mean the next larger element or the element with the minimal distance? In the 2nd case, the answer would be 0.49, in opposite to your example.

Teemu

### Teemu (view profile)

on 5 Mar 2013

Minimal distance, in this case it will be 0.49

Teemu

### Teemu (view profile)

on 5 Mar 2013

actually I need both

## Products

No products are associated with this question.

## 3 Answers

### Jos (10584) (view profile)

Answer by Jos (10584)

### Jos (10584) (view profile)

on 4 Mar 2013
Accepted answer

Here is one approach:

```   v = [0.1 0.23 0.4 0.52 0.56 1.1]
idx = find(v >= 0.5,1,'first')
v(idx)```

Teemu

### Teemu (view profile)

on 5 Mar 2013

So how can I do minimal distance pick?

Jan Simon

### Jan Simon (view profile)

on 5 Mar 2013

Please, Teemu, read my answer below. There you find the code to pick the element with the minimal distance. It is the 2nd line and the index is the 2nd output of min(abs(v - 0.5)).

Teemu

### Teemu (view profile)

on 5 Mar 2013

Sorry I didn't noticed that, I thought it was answer for next index. Thanks for your patience.

### Jos (10584) (view profile)

Answer by Jos (10584)

### Jos (10584) (view profile)

on 5 Mar 2013

To do this for multiple values, take a look at my function NEARESTPOINT:

http://www.mathworks.com/matlabcentral/fileexchange/8939

### Jan Simon (view profile)

Answer by Jan Simon

### Jan Simon (view profile)

on 4 Mar 2013
Edited by Jan Simon

### Jan Simon (view profile)

on 5 Mar 2013
```v                = [0.1 0.23 0.4 0.52 0.56 1.1];
[absdist, nearest] = min(abs(v - 0.5));  % **SOLUTION IS HERE** !!!
if absdist == 0  % or: <= eps(v(index))
following = index;
else
following = index + 1;
end
```
```nearestValue   = value(nearest);
followingValue = value(following);
```

#### 0 Comments

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

### Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

### MATLAB Academy

New to MATLAB?

Learn MATLAB today!