필터 지우기
필터 지우기

Array Indice Error For Loop

조회 수: 2 (최근 30일)
HoboHarry
HoboHarry 2018년 10월 25일
편집: Stephen23 2018년 10월 25일
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