- Initialization: Ensure that "r" is initialized correctly before using it in the loop, and check for "r == 0" to prevent division by zero.
- Accumulating the Sum: Make sure "G1" accumulates the computed "term" in each iteration.
- Variable Update: Reset "nx" at the start of each iteration of the outer loop to correctly iterate over "ny."
Loop Sum over two arrays
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
I need to solve an infinite sum over two variables. The sum should converge, but I cannot get my loop to accurately give the values expected for a given value of the two variables. My loop appears as such:
nx = 0;
ny = 1;
G1 = 0;
for n = 1:100
for m = 1:100
G1 = (1/(4*pi*sqrt((nx^2)+(ny^2)))*(cos(k*r) - sin(k*r)/(k*r) - cos(k*r)/((k*r)^2) + (-cos(k*r) + 3*(cos(k*r) + (k*r)*sin(k*r)/((k*r)^2)))*(nx^2)/((nx^2)+(ny^2))));
nx = nx + 1;
r = a*sqrt((nx^2)+(ny^2));
end
%G1 = G1 + G1 = (1/(4*pi*sqrt((nx^2)+(ny^2)))*(cos(k*r) - sin(k*r)/(k*r) - cos(k*r)/((k*r)^2) + (-cos(k*r) + 3*(cos(k*r) + (k*r)*sin(k*r)/((k*r)^2)))*(nx^2)/((nx^2)+(ny^2))));
ny = ny + 1;
end
The idea is for my equation to solve for when nx = 0 and ny = 1, then solve for when nx = 1 and ny =1, then nx = 2 and ny = 1, etc. until nx =100 while ny = 1 still. This should repeat for ny =2, ny =3, etc and summing all values along the way. I have considered trying to nx and ny to an array and using that method, but I'm not terribly sure how I would approach that either.
I have a separate program with just the G1 equation and arbitrary values for nx and ny so I can see if checking different parameters on my loop will yield accurate values for a given set of nx and ny values, but I can only get accurate results for nx = 0, ny =1 or nx =1, ny =0. Any help or advice would be greatly appreciated.
1 comentario
Omega
el 20 de Sept. de 2024
Hi Chirs,
I understand that you want to sum an infinite series over two variables, "nx" and "ny", using a loop in MATLAB. Your loop has a few issues that need to be addressed to correctly compute the sum over "nx" and "ny." You can follow the steps below to resolve these issues:
Here's a sample code incorporating the steps mentioned above.
nx_max = 100;
ny_max = 100;
G1 = 0;
a = 1; % Ensure 'a' is defined
k = 1; % Ensure 'k' is defined
for ny = 1:ny_max
for nx = 0:nx_max
r = a * sqrt((nx^2) + (ny^2));
if r == 0
continue; % Avoid division by zero for r
end
term = (1 / (4 * pi * sqrt((nx^2) + (ny^2)))) * ...
(cos(k * r) - sin(k * r) / (k * r) - cos(k * r) / ((k * r)^2) + ...
(-cos(k * r) + 3 * (cos(k * r) + (k * r) * sin(k * r)) / ((k * r)^2)) * (nx^2) / ((nx^2) + (ny^2)));
G1 = G1 + term;
end
end
disp(G1);
Respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!