Error in following matlab code.

Error in following codes
for i = 1:12
if i == 12
x1 = 9
end
x1 = [1];
x2 = [3];
if i == 1
x1 = 2
else
x1(i) = x1(i-1) - x2;
end
x = [x1 x2]
end
When i run it it shows following error please help me to solve error.
Array indices must be positive integers or logical values.

3 件のコメント

madhan ravi
madhan ravi 2019 年 1 月 26 日
編集済み: madhan ravi 2019 年 1 月 26 日
What is your desired result ? Give an example.
Usman Taya
Usman Taya 2019 年 1 月 26 日
I want 12 values of x1 and x2 where current x1 from i = 2 to 12 will calculate using x1(i) = x(i-1) -x2.
Image Analyst
Image Analyst 2019 年 2 月 3 日
Yes, but did Star's answer below solve your problem or not? Did you even try it?

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

回答 (1 件)

Star Strider
Star Strider 2019 年 1 月 26 日

0 投票

The error comes from your current calculation of ‘x1’ as:
x1(i) = x1(i-1) - x2;
In the first iteration,i=1 so (i-1)=0. In MATLAB, indices are integers greater than 0, or logical values.
I am not certain this ‘corrected’ version of your code creates the values for ‘x’ that you want. However, it has the virtue of running without error:
for i = 1:12
if i == 12
x1(i) = 9;
end
x1(i) = [1];
x2 = [3];
if i == 1
x1(i) = 2;
else
x1(i+1) = x1(i) - x2;
end
x(i,:) = [x1(i) x2];
end
Experiment to get the result you want.

カテゴリ

質問済み:

2019 年 1 月 26 日

コメント済み:

2019 年 2 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by