# How to create a for loop with a set of variables

3 views (last 30 days)
Gabrielle Pinto on 3 Oct 2022
Answered: Steven Lord on 3 Oct 2022
Hello, I want to create a for loop but I'm unsure how. I have my code written out, I just want to substitute h with 11 different values, I assigned them to variables h1 through h11. Is there a way I can create a for loop for this code to run with my different h values? In this code I have it written as h1, because currently I ran this code through 11 different times to get each set with different h values.
h1 = 1694;
h2 = 1686;
h3 = 1645;
h4 = 1561;
h5 = 1502;
h6 = 1240;
h7 = 995;
h8 = 815;
h9 = 690;
h10 = 514;
h11 = 318;
% Determine C0, and Cg0
% C0 = L0/T0, simplifies to gT/2pi
T = 46.7;
H0 = 56.47;
g = 9.81;
C0 = (g*T)/(2*pi);
Cg0 = C0/2;
% Use LDR to find the wavelength at h = 3 m
% Linear Dispersion Relationship
h1 = 1694;
a = (g*T.^2)./(2*pi);
b = 2*pi*h1;
epsilon = 0.001;
flag = 0;
L0 = 0.01;
% Wavelength
while flag == 0
f_L = L0-a.*tanh(b./L0);
f_L_prime = 1 - (a*b*(tanh(b/L0)^2 - 1))/L0^2;
% Newton's Method
L1 = L0 - f_L/f_L_prime;
if abs (L1-L0) <= epsilon
flag = 99;
end
L0=L1;
end
L=L1;
% Calculate c and k from LDR
k = (2*pi)/L;
c = L/T;
Cg1 = (c/2).*(1 + (2*k*h1)./(sinh(2*k*h1)))
% Shoaling Coefficient
Ks = ((C0/2)./((c/2).*(1+((2*k*h1)./(sinh(2*k*h1)))))).^0.5;
% or (these values will be the same)
Ks1 = (Cg0/Cg1).^0.5
H1 = H0*Ks

Steven Lord on 3 Oct 2022
Can you dynamically create variables with numbered names like h1, h2, h3, etc. and refer to those variables dynamically in code? Yes.
Should you do this? The general consensus is no. That Answers post explains why this is generally discouraged and offers several alternative approaches. The simplest would probably be to create a vector h and use h(1), h(2), h(3), etc. wherever you would have used h1, h2, h3, etc. in your original code.