problem with loops and conditional statements

5 ビュー (過去 30 日間)
bhawna
bhawna 2024 年 8 月 11 日
コメント済み: bhawna 2024 年 8 月 11 日
I am writing a simple program with if loop inside a for loop but the program gets stopped in middle with error:
Index exceeds the number of array elements. Index must not exceed 1.
Error in newtrial (line 19)
Y(i) = Y(i) + 1;
and the plot is not generated as well even for values generated.
the code is:
clc
clear
x1 = 5
x1 = 5
y1 = 3
y1 = 3
x0 = 0
x0 = 0
y0 = 0
y0 = 0
dx = x1-x0
dx = 5
dy = y1-y0
dy = 3
e = dy-dx
e = -2
X = x0
X = 0
Y = y0
Y = 0
for i = 1:1:5;
X(i+1) = X(i) + 1
if e(i) >= 0
Y(i+1) = Y(i) + 1;
e(i+1) = e(i) - dx;
else
e(i+1) = e(i) + dy;
end
end
X = 1x2
0 1
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
X = 1x3
0 1 2
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Index exceeds the number of array elements. Index must not exceed 1.
Y
plot(X,Y,'bo')
axis([0 6 0 6])
I am new to this, so any help or correction in code is appreciated, thanks in advance.

採用された回答

AMIT
AMIT 2024 年 8 月 11 日
the problem is with the statement Y(i+1) = Y(i) + 1; in the second iteration it is trying to update the Y(3) with Y(2)+1 when during the first iteration the value of Y(2) is not updated in the else statement. try to rectify within the else statement for Y.
  1 件のコメント
bhawna
bhawna 2024 年 8 月 11 日
It worked, Thank You so much.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by