Having trouble with Complicated for loop

1 view (last 30 days)
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.

Accepted Answer

Star Strider
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
Joshua
Joshua on 21 Oct 2014
Ahhhh Finally!!! I was able to figure out how to do the loop the way I wanted to. I did what you suggested, it didn't quite function properly but I just added a little tweek with the "if' statement and it worked magically.
my loop resembles this now
for h = 1:5 % Loop for the 5 days
if h > 1
To(:,1) = To(:,t+1);
end
for t = 1:24 %Hours
"B(m,n) = Values...."
X(:,t) = A\B;
X = round(X/0.01)*0.01;
Tn = X;
To(:,t+1) = Tn(:,t);
end
end
I can't Thank you enough for helping me. I sincerely appreciate your time in helping me. After many days of working on it and asking around for help, it finally works. Thank you once again.
Star Strider
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.

Sign in to comment.

More Answers (0)

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!