Array Indice Error For Loop

Following code is coming up with error "Array indices must be positive integers or logical values."
Does someone know what is causing this. Trying to store each value into an array
z =@(x) tan(x);
h = 0.5
for x=1:0.5:10
Output (x) = (z(x+h)-z(x-h))/(2*h);
end
Array = [Output]

1 Comment

Note that your code can be trivially vectorized (a loop is a waste of time):
z = @tan;
h = 0.5;
x = 1:0.5:10;
y = (z(x+h)-z(x-h))./(2*h);
Learn how to write neat and efficient MATLAB code:

Sign in to comment.

 Accepted Answer

madhan ravi
madhan ravi on 25 Oct 2018
Edited: madhan ravi on 25 Oct 2018
z =@(x) tan(x);
h = 0.5
x=1:0.5:10
Output = zeros(1,19) %preallocation for speed and efficiency
for i = 1:numel(x)
Output (i) = (z(x(i)+h)-z(x(i)-h))/(2*h);
end
Array = Output

3 Comments

you can access x(1.5)->(second iteration) because indexing should be real integers
@madhan ravi: where is the array preallocation? What do those square brackets do? (Hint: nothing)
Thank you Stephen (edited now)

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 25 Oct 2018

Edited:

on 25 Oct 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!