필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Is there no better way to save this For loop data?

조회 수: 1 (최근 30일)
Alejandro
Alejandro 2014년 10월 8일
마감: MATLAB Answer Bot 2021년 8월 20일
x=30;
for i=2:22
x = (x(i-1)*0.02)+x(i-1)
end
The loop does as intended but it feels very hacky and like there is a cleaner way to do this without having to resort to having an index start from 2 rather than 1.
The code is just meant to calculate a 2 percent increase in price per year.
I resorted to this because the initial code would work but not save the data:
x=30;
for i=0:20
x = (x*0.02)+x
end

답변 (1개)

Image Analyst
Image Analyst 2014년 10월 8일
It's not quite right. You need x(i) on the left hand side, like this:
x=30;
for i=2:22
x(i) = (x(i-1)*0.02)+x(i-1)
end
plot(x, 'b*');
Other than that, it's fine, not hacky. It's easy to understand and simple and fast, so there's no problem. Sure there are other ways, but why? They could be more cryptic, not intuitive, or hard to follow.

Community Treasure Hunt

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

Start Hunting!

Translated by