Using repeating loops to calculate profits
조회 수: 1 (최근 30일)
이전 댓글 표시
Write a program which calculate the total profit/year by the end of each month in a year, given the variable P which stores profit/month for that year:
P= [10 7 5 4 6 8 1 6 8 5 11 12]*1000
Set up a loop to calculate Ptotal(i+1)=Ptotal(i)+P(i+1), to help decide about start/end conditions, use an iteration table.
clear
clc
P= [10 7 5 4 6 8 1 6 8 5 11 12]*1000;
Ptot = 1;
for i = 1:length(P)
if Ptot(i)==1
Ptot=P
else
Ptot(i+1) = Ptot(i)+P(i+1)
end
end
disp(Sum);
Could someone help me with this, i've been stuck on this question for a while and just kind of lost? I did a similar question earlier and got the right answer but because the index is start at 0 instead of 1 is making me kind of confused on how to go about this question?
Thanks for the help!
댓글 수: 0
답변 (1개)
Ashutosh Thakur
2022년 6월 30일
You can follow this code for understanding about start/end conditions
P= [10 7 5 4 6 8 1 6 8 5 11 12]*1000;
Ptot(1) = P(1);
for i = 1:length(P)-1
Ptot(i+1) = Ptot(i) + P(i+1);
end
disp(Ptot)
You can initialize Ptot(1) with P(1) and run the loop till length(P) - 1 because you are incrementing Ptot by i+1.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!