For loop to add elements in a vector

49 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by