필터 지우기
필터 지우기

Variable updated in for loop iteration

조회 수: 11 (최근 30일)
Davide Frattini
Davide Frattini 2023년 7월 8일
댓글: Davide Frattini 2023년 7월 8일
I have a very simple code that do not update the variable in the array during the for loop interation. It works if I run the for loop as i = 1. In that cas I can see that revenue(1) and budget_i(2) report the correct values. When the for loop interation exceed 1 interation, the arrays revenue and budget_i are no longer updated.
close = [0.01110 0.03600 0.01810 0.0208 ... 0.06470 0.00120]; % originally 126 values
revenue = zeros(1,126);
budget_i = zeros(1,126);
budget_i(1) = 100;
for i = 1
revenue(i) = budget_i(i) +(budget_i(i)*close(i));
if close(i) > 0
budget_i(i+1) = revenue(i) + 100;
elseif close(i) < 0
budget_i(i+1) = revenue(i) + 200;
end
end
%% here I have, correcly, budget_i(1) = 100; revenue(1) = 101.11; budget(2) = 201.11.
at this point I was expecting the revenue(2) calculation to work perfectly using budget_i(2) that I defined in the previous iteration but all I get in the variable array is a zero. Also revenue(1) is zero.
The code should work with for loop as for i = length(close) but revenue(i) and budget_i(i) failed to update and all I get is two arrays as revenue = zeros(1,126) and budget_i = zeros(1,126) with budget_i(1) = 100.
Any idea why it doesn't work at iteration greater than 1?

채택된 답변

Vilém Frynta
Vilém Frynta 2023년 7월 8일
I tested your code and revenue and budget_i were being updated.
I have no idea what the purpose of your script is, and thus I don't know you want to work with it, but if you were putting
for i = 2
then it didn't work. But if i input
for i = 1:2
then it works.
  댓글 수: 1
Davide Frattini
Davide Frattini 2023년 7월 8일
Very stupid mistake of mine in defining the iteration rule. Thanks a lot!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by