For loop to add elements in a vector

조회 수: 13 (최근 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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by