Parameter sweep without nested for loop

조회 수: 2 (최근 30일)
KAE
KAE 2018년 11월 28일
편집: KAE 2018년 11월 29일
The following parameter sweep has many nested loops. How can I eliminate the nested loops with linear indices, but be able to access the evaporation value afterward for parameter values of temperature=75, humidity=40, and windSpeed=5? (The arithmetic line is a placeholder for a more complex calculation, so I don't want to elimate loops entirely). I know there are existing examples but I am struggling with the basics.
temperature = 70:5:90;
humidity = 30:10:100;
windSpeed = [2 5 10 20];
for iT = 1:length(temperature)
for iH = 1:length(humidity)
for iW = 1:length(windSpeed)
% Simple arithmetic placeholder for a more complex function
evaporation(iT, iH, iW) = temperature(iT) + humidity(iH) - windSpeed(iW);
end
end
end
% Access evaporation for temperature=75, humidity=40, and windSpeed=5
evaporation(temperature==75, humidity==40, windSpeed==5)

채택된 답변

KAE
KAE 2018년 11월 29일
편집: KAE 2018년 11월 29일
Here is one solution using allcomb, but is there a better way? By "better" I mean "easy to understand what the code is doing, yet faster than nested loops."
temperature = 70:5:90;
humidity = 30:10:100;
windSpeed = [2 5 10 20];
% Matrix containing all combinations of parameters
parameterMatrix = allcomb(temperature, humidity, windSpeed);
% Matrix containing index to all combinations of parameters
indexToParameterMatrix = allcomb(1:length(temperature), ...
1:length(humidity), ...
1:length(windSpeed));
nCase = size(parameterMatrix, 1); % Number of parameter combinations
for iCase = 1:nCase % Loop through each combination of parameters
iT = indexToParameterMatrix(iCase, 1); % Index to temperature value
iH = indexToParameterMatrix(iCase, 2); % Index to humidity value
iW = indexToParameterMatrix(iCase, 3); % Index to windSpeed value
% Simple arithmetic placeholder for a more complex function
evaporation(iT, iH, iW) = ...
parameterMatrix(iCase,1) + ... % temperature value
parameterMatrix(iCase,2) - ... % humidity value
parameterMatrix(iCase,3); % windSpeed value
end
% Access evaporation for temperature=75, humidity=40, and windSpeed=5
evaporation(temperature==75, humidity==40, windSpeed==5)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by