Ho do I save the values of While at each hour?
Show older comments
For a while loop how I can calculate the values at each hour before do a break? As we know while loop only performs the condition statment and breaks the loop, then gives you the value at that specific hour only. I provide te example below :
for i=1:Time
while water_tank_soc(i-1) < Water_tank_capacity_max
m_net_o(i) =.........
m_net_i(i) = ......
% Update SOC
water_tank_soc(i) = water_tank_soc(i-1) + m_net_i(i) - m_net_o(i);
if water_tank_soc(i) >= Water_tank_capacity_max
break
end
% Update for next time step
water_tank_soc(i-1) = water_tank_soc(i); % Update previous state for next iteration
end
end
5 Comments
Walter Roberson
on 3 Aug 2024
That code appears to have the problem of water_tank_soc(i-1) not having been defined.
For the code to work,
water_tank_soc = zeros(1,Time-1);
would have to be executed first.
dpb
on 3 Aug 2024
You would then have to doubly dimension the array and then the second dimension would have to be as wide as the maximum number of iterations or, the simpler would probably be to use a cell array at each hour to hold the iterations saving only the final as the double as present. The cell array can hold as many or as few as are in each hour.
Alhussain
on 3 Aug 2024
dpb
on 3 Aug 2024
@Walter Roberson did for you...
Accepted Answer
More Answers (1)
Walter Roberson
on 3 Aug 2024
Adjusted to save each iteration. A cell array is used because different iterations might run the while loop for different number of steps.
saved_soc = cell(1, Time);
for i=1:Time
saved_soc{i} = water_tank_soc(i-1);
while water_tank_soc(i-1) < Water_tank_capacity_max
m_net_o(i) =.........
m_net_i(i) = ......
% Update SOC
water_tank_soc(i) = water_tank_soc(i-1) + m_net_i(i) - m_net_o(i);
if water_tank_soc(i) >= Water_tank_capacity_max
break
end
% Update for next time step
water_tank_soc(i-1) = water_tank_soc(i); % Update previous state for next iteration
saved_soc{i}(end+1) = water_tank_soc(i-1};
end
end
2 Comments
Alhussain
on 4 Aug 2024
Walter Roberson
on 4 Aug 2024
No, the logic associated with saved_soc{i}(end+1) is saving every while loop iteration for every timestep, not just one hour.
Categories
Find more on C2000 Microcontroller Blockset 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!