Parameter sweep without nested for loop

8 vues (au cours des 30 derniers jours)
KAE
KAE le 28 Nov 2018
Modifié(e) : KAE le 29 Nov 2018
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)

Réponse acceptée

KAE
KAE le 29 Nov 2018
Modifié(e) : KAE le 29 Nov 2018
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)

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by