Variable updated in for loop iteration

14 次查看(过去 30 天)
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.

更多回答(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