Array Indice Error For Loop

1 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2018-10-25
编辑:Stephen23 2018-10-25
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:

请先登录,再进行评论。

采纳的回答

madhan ravi
madhan ravi 2018-10-25
编辑:madhan ravi 2018-10-25
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 个评论
Stephen23
Stephen23 2018-10-25
@madhan ravi: where is the array preallocation? What do those square brackets do? (Hint: nothing)
madhan ravi
madhan ravi 2018-10-25
Thank you Stephen (edited now)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by