How to run a script multiple times changing one variable?

I want to be able to run the below script multiples times, each time for a different value of Dd. Ending up with a file that gives me Scrit for each Dd.
Do I do this using a for loop?
% Using dry diameter in um
K=0.5;
Dd=0.1;
sigma=0.072;
T=298.15;
Mw=18.01528;
Pw=0.997;
R=8.3143;
% Define functions
D=linspace(0.1,5,500);
% Define exponential constants as a function
x=(4*sigma*Mw)/((R*T*Pw));
S=((D.^3-Dd^3)./(D.^3-Dd^3+Dd^3*K)).*exp(x./D);
plot(D,S)
% Labelling the axes
xlabel('Wet Diameter (um)')
ylabel('Saturation')
title('Kohler Curves for Different Diameter')
% Limits for axes
ylim([0.98,1.05])
xlim([0.1,5])
% Finding the maximum in a data set
Scrit=max(S)
Dmax=D(find(S==Scrit))
I had a go and this is what i have so far:
for Dd=0.01:0.01:5;
D=linspace(0.1,5,500);
x=(4*sigma*Mw)/((R*T*Pw));
S=((D.^3-Dd^3)./(D.^3-Dd^3+Dd^3*K)).*exp(x./D); % Loop
end

1 Kommentar

Alice - yes, you could use a for loop (though you would need to store the results (i.e. the S) for each iteration so that you could plot all results outside of the loop. Note that in your code, you could move the initialization of D and x outside of the loop since neither depends upon the value of Dd.
Or, you could try vectorization which may work nicely with your code.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Star Strider
Star Strider am 28 Feb. 2019
Go with vectorization!
Try this:
% Using dry diameter in um
K=0.5;
Dd=0.1;
sigma=0.072;
T=298.15;
Mw=18.01528;
Pw=0.997;
R=8.3143;
% Define functions
D=linspace(0.1,5,500);
% Define exponential constants as a function
x=(4*sigma*Mw)/((R*T*Pw));
S = @(D) ((D.^3-Dd^3)./(D.^3-Dd^3+Dd^3*K)).*exp(x./D);
Sm = S(D);
plot(D,Sm)
% Labelling the axes
xlabel('Wet Diameter (um)')
ylabel('Saturation')
title('Kohler Curves for Different Diameter')
% Limits for axes
ylim([0.98,1.05])
xlim([0.1,5])
% Finding the maximum in a data set
Scrit=max(Sm(:))
Dmax=D(find(Sm==Scrit))
text(Dmax, Scrit, sprintf('D_{max} = %.3f\nS_{crit} = %.3f\n\\downarrow', Dmax, Scrit), 'VerticalAlignment','bottom')

2 Kommentare

Thank you for your help.
I'm just unsure of how to get Scrit for different values of Dd? Should I just be using a for loop with vectorisation? I don't really understand what the vectorisation has done? (sorry I'm very new to this!)
Basically I want Scrit from a graph of S against D for multiple values of Dd.
My pleasure.
Basically I want Scrit from a graph of S against D for multiple values of Dd.
I believe my code does exactly that. Did you run it? If so, did it do what you want?

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by