Having trouble with Complicated for loop
1 view (last 30 days)
Show older comments
I have created this program, but having issues with my loop. My program is suppose to do calculation 24 times within a loop of 5. so intotal i have 120 iterations, and at each iteration the new values become the old values for the following iteration. my problem is that I can't get my 24th value to become my first value of the next loop.
for example my loop looks like this:
To = 20; %initial value
for h = 1:5 % days
for t = 1:24 %hours
MatrixB (1,2) = To* "Values"
X(:,t) = A\B;
Tn = X; % New Temp
To(:,t+1) = Tn(:,t); %new temp becoming old temp for next iteration
end
end
now my issue is trying to get the value on the 24th hour on day 1 to become my initial value of To on hour 1 of day 2 so that I can continue the iteration for another 4 days. so far my values are the same for each day which cannot be.
0 Comments
Accepted Answer
Star Strider
on 20 Oct 2014
I couldn’t run your code, so I did the best I could to simulate it. Here, ‘X’ updates and carries over. See if it works with your calculations:
X = zeros(2, 5, 24); % Preallocate
To = [0; 0]; % Initial Carryover Matrix
for h = 1:5
if h > 1
To = X(:,(h-1),24); % Last Matrix (Days 2-5)
end
for t = 1:24
X(:,h,t) = [h; t] + To; % Calculations
end
end
Q = X(:,:,24); % Selected Output (Discard)
Update the preallocation step with the number of rows in ‘X’ in your calculations. (I used 2 here.)
7 Comments
Star Strider
on 21 Oct 2014
My pleasure!
I wasn’t quite sure how to set the carry-over value of ‘To’, but I knew the solution was to define it at the start of the ‘h’ loop. My contribution was in part just having seen it for the first time! I’m happy you got it to work.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!