MATLAB Answers

## Why does the Index exceeds the number of array elements

Asked by Wilfredo Huaman

### Wilfredo Huaman (view profile)

on 14 Jun 2019
Latest activity Commented on by Wilfredo Huaman

### Wilfredo Huaman (view profile)

on 14 Jun 2019
Accepted Answer by Geoff Hayes

### Geoff Hayes (view profile)

Im trying to run through total Force which is a 921x1 Double and check if the next value in that array is larger or greater if larger i want to subtract 0.01 from c and if smaller I want to add 0.01 to c and c starts at zero. Why does it exceed the index? Any Help would be greatly Appreciated Thanks!
for j = 1:length(TotalForce)
if j <= length(TotalForce)
if TotalForce(j) >= TotalForce(j+1)
c = c + 0.01 ;
elseif TotalForce(j) <= TotalForce(j+1)
c = c - 0.01 ;
end
end
end

#### 0 Comments

Sign in to comment.

R2019a

## 1 Answer

Answer by Geoff Hayes

### Geoff Hayes (view profile)

on 14 Jun 2019
Accepted Answer

Wilfredo - take a look at these lines
for j = 1:length(TotalForce)
if j <= length(TotalForce)
if TotalForce(j) >= TotalForce(j+1)
If j happens to be the length of the TotalForce array, then j+1 will be an invalid index into your array. Try doing something like
for j = 1:length(TotalForce)-1
if TotalForce(j) >= TotalForce(j+1)
c = c + 0.01 ;
else
c = c - 0.01 ;
end
end

Wilfredo Huaman

### Wilfredo Huaman (view profile)

on 14 Jun 2019
Thank you Worked Great!

Sign in to comment.