Error ''Array indices must be positive integers or logical values.'' when putting interval of 0.01 in a for loop
    조회 수: 32 (최근 30일)
  
       이전 댓글 표시
    
I get an error ''Array indices must be positive integers or logical values.' when i'm trying to execture a for loop with an interval of 0.01, however when the interval is 1, everything is fine. The problem may stem from it not allowing negative numbers in the array.
y = [];
x = [];
for i = 0:0.1:2
    x(i+1) = i
    y(i+1) = i*i + 3*i - 4
end
plot(x,y)
This is the entire code, nothing more
댓글 수: 0
답변 (3개)
  Dyuman Joshi
      
      
 2024년 1월 2일
        The problem stems from the use of 0 and non-integer values as indices. 
As the error message states - Arrays indices in MATLAB must be positive integers (or logical values).
You can vectorize your code - 
i = 0:0.1:2;
x = i;
y = i.*i + 3*i - 4;
plot(x,y)
댓글 수: 0
  Vignesh
 2024년 1월 2일
        Hi Rinalds,
You are encountering this error because you are giving a decimal as index of an array in the for loop. You may try changing the following line according to the number of times you want to iterate the loop.
for i = 0:0.1:2
댓글 수: 0
  Alan Stevens
      
      
 2024년 1월 2일
        More like this:
k = 0:0.1:2;
n = numel(k);
for i = 1:n
    x(i) = k(i);
    y(i) = k(i)*k(i) + 3*k(i) - 4;
end
plot(x,y)
댓글 수: 0
참고 항목
카테고리
				Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!




