I want to perform the following calculations using for loops. I have assigned values to variables A and B. I want to calculate V, by plugging k=0:0.1:x and setting a condition inside the for loop. If k<=5 calculate V=(-A)(k)+(B*6) and else V=(-A)(k)+(B*6)+(A/B)(k). How can i make it work using for loops and how can i stored every value?
x=input('From zero, until what number do you want to calculate');
A=5;
B=2;
for k=0:0.1:x
if k<=5
V=(-A)*(k)+(B*6);
else
V=(-A)*(k)+(B*6)+(A/B)*(k)
end
V(k)=V;
end

1 件のコメント

Sindar
Sindar 2020 年 3 月 6 日
what error messages?

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

 採用された回答

Sindar
Sindar 2020 年 3 月 6 日
編集済み: Sindar 2020 年 3 月 6 日

2 投票

Two problems:
  • parentheses are not multiplication in matlab, you need *
  • you are trying to insert a variable into itself
Solution (edited for modified question):
x=input('From zero, until what number do you want to calculate');
A=5;
B=2;
kvec = 0:0.1:x;
for ind=1:length(kvec)
if kvec(ind) <= 5
V(ind)=-A*kvec(ind)+B*6;
else
V(ind)=-A*kvec(ind)+B*6+A/B*kvec(ind)
end
end

2 件のコメント

Sindar
Sindar 2020 年 3 月 6 日
BTW, this can be done without loops or if statements:
V(1:5) = -A*(1:5)+B*6;
V(6:10) = -A*(6:10)+B*6+A/B*(6:10);
Sindar
Sindar 2020 年 3 月 6 日
(you can still do it without loops, think about how)

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2020 年 3 月 6 日

コメント済み:

2020 年 3 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by