我知道矢量化代码比使用循环更快,所以我一直在尝试使用此代码。我希望有人能告诉我如何改进这些for
和if
循环。该程序旨在计算房屋的电力负荷曲线,同时考虑不同的电器在一天、一个月和一年的不同时间是打开还是关闭。
、等是概率矩阵ProbFanSummerWd
,ProbCellChargerSummerWd
用于根据先前的随机“选择”来决定电器是打开还是关闭;TotalLoad
是合成功率曲线。这个函数在一个较大的程序中会重复很多次,并且会消耗很多时间。
我该如何改进这些for
和if
循环?如何用矢量化替换它们?
我希望有人能帮助我。非常感谢。
HourCount = 0;
for DayYear = 1:size(Season,2) %LOOP - ONE YEAR
if Season(DayYear) == 1 %LOOP - SUMMER SEASON
if WeekDay(DayYear)>=1 && WeekDay(DayYear)<=5 %SUMMER WEEKDAY
for Hour = 1:24 %LOOP - ONE DAY
HourCount = HourCount+1;
for h = 1:NumHouse %LOOP - HOUSE
Choose = rand(1); %CellCharger
if Choose <= ProbCellChargerSummerWd(Hour)
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ PowCellCharger;
else
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ StandByCellCharger;
end
Choose = rand(1); %Fan
if Choose <= ProbFanSummerWd(Hour)
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ PowFan;
else
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ StandByFan;
end
Choose = rand(1); %Fridge
if Choose <= ProbFridgeSummerWd(Hour)
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ PowFridge;
else
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ StandByFridge;
end
Choose = rand(1); %Heater
if Choose <= ProbHeaterSummerWd(Hour)
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ PowHeater;
else
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ StandByHeater;
end
Choose = rand(1); %Iron
if Choose <= ProbIronSummerWd(Hour)
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ PowIron;
else
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ StandByIron;
end
Choose = rand(1); %LampKitchen
if Choose <= ProbLampKitchenSummerWd(Hour)
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ PowLampKitchen;
else
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ StandByLampKitchen;
end
Choose = rand(1); %LampRoom
if Choose <= ProbLampRoomSummerWd(Hour)
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ PowLampRoom;
else
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ StandByLampRoom;
end
Choose = rand(1); %Radio
if Choose <= ProbRadioSummerWd(Hour)
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ PowRadio;
else
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ StandByRadio;
end
Choose = rand(1); %TV20
if Choose <= ProbTvSummerWd(Hour)
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ PowTv;
else
TotalLoad(1,HourCount) = TotalLoad(1,HourCount)+ StandByTv;
end
end
end