For loop to add elements in a vector

9 ビュー (過去 30 日間)
Huereka Aragon
Huereka Aragon 2021 年 2 月 28 日
回答済み: KALYAN ACHARJYA 2021 年 3 月 1 日
Hello,
I wanted to come up with a for loop statement where all of my elements add up together given a formula to get each element, x(1) and length of the x vector
x=zeros(15,1);
x(1)=50;
x(2)=x(1)+(x(1)*0.005)+200;
x(3)=x(2)+(x(2)*0.005)+200;
x(4)=x(3)+(x(3)*0.005)+200;
and etc
formula used to get each element is x(n)=(x(n)-1)+((x(n)-1)*0.005)+200 and
I mean i can do what i did up until 15 but is i know for loop is more convenient.
i tried
x=zeros(15,1);
x(1)=50;
for iv=2:length(x)
x(iv)= (x(iv-1))+((x(iv-1))*0.005)+200;
end
summ=sum(x);
disp(summ);
but doesnt seem to work

回答 (1 件)

KALYAN ACHARJYA
KALYAN ACHARJYA 2021 年 3 月 1 日
% Set the format as per how numbers should appear in Command Window output
format shortG
Next:
x=zeros(15,1);
x(1)=50;
for i=2:length(x)
x(i)=x(i-1)+x(i-1)*0.005+200;
end
x
x =
50
250.25
451.5
653.76
857.03
1061.3
1266.6
1473
1680.3
1888.7
2098.2
2308.7
2520.2
2732.8
2946.5
Sum of the array x
summ=sum(x);
disp(summ);
22239

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by