For loop to add elements in a vector
13 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponses (1)
KALYAN ACHARJYA
le 1 Mar 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
0 commentaires
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!