For loop to add elements in a vector

59 Ansichten (letzte 30 Tage)
Huereka Aragon
Huereka Aragon am 28 Feb. 2021
Beantwortet: KALYAN ACHARJYA am 1 Mär. 2021
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

Antworten (1)

KALYAN ACHARJYA
KALYAN ACHARJYA am 1 Mär. 2021
% 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

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by