Clear Filters
Clear Filters

Variable updated in for loop iteration

14 views (last 30 days)
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?

Accepted Answer

Vilém Frynta
Vilém Frynta on 8 Jul 2023
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 Comment
Davide Frattini
Davide Frattini on 8 Jul 2023
Very stupid mistake of mine in defining the iteration rule. Thanks a lot!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!