While loop within for loop problem
3 views (last 30 days)
Show older comments
Hello all,
I am writing a simple code to calculate the electric field strength in the insulation of a cable directly from the Maxwell equations at each time step. I want to iterate every time step until error is less than 0.1% to make my solution accurate. The code is not working properly because the while loop iterates only once in the first iteration of the r loop and I have no idea why ... ?
Here is the part of code:
z = size(Y_temp,1);
for r = 2:z-1
V(r,1) = 450 + r; V(r,end) = 0;
while error3 > tolerance %&& error4 > tolerance && error5 > tolerance && error6 > tolerance
V_old = V;
for c = 2:numel(r1)-1
ch(r,c) = ch(r-1,c) - (t/(2*h1)) * (J(r,c+1) - J(r,c-1)) %charge from current continuity
V(r,c) = (h1/(4*r1(i))) * (V(r,c+1) - V(r,c-1)) + (V(r,c+1) + V(r,c-1))/2 + ((h1^2)/(2*epsilon)) * ch(r,c); %electric potential for Poissons equation
E(r,c) = (-V(r,c+1) + V(r,c-1))/(2*h1); %Irrotational electric field
sigma(r,c) = sigma_0 * exp(alpha_T * Y_temp(r,c)) * exp(gamma_E * E(r,c)); %empiric equation of conductivity
J(r,c) = sigma(r,c) * E(r,c); %Ohm's law
end
error3 = max(abs((V - V_old) ./V_old));
end
end
Thank you very much in advance for your help.
1 Comment
Answers (2)
Swati Khese
on 8 Aug 2023
I think there is problem in this line "z = size(Y_temp,1);"
Maybe Y_temp is a vector with two rows, so z becomes 2 and for loop runs for only once.
Can you share size of Y_temp variable? [size(Y_temp)]
Kamil
on 1 Sep 2023
5 Comments
Torsten
on 22 Sep 2023
Here is a very primitive Newton method. Or use "Octave".
f = @(x)[x(1)^2-3;x(1)*x(2)-3.5];
u0 = [1;1];
sol = nls(f,u0)
function u = nls(f,uold)
u = zeros(numel(uold),1);
itermax = 30;
eps = 1e-6;
error = 1.0e5;
uiter = uold;
iter = 0;
while error > eps && iter < itermax
u = uiter - Jac(f,uiter)\f(uiter);
error = norm(u-uiter);
iter = iter + 1;
uiter = u;
end
iter
end
function J = Jac(f,u)
y = f(u);
h = 1e-6;
for i = 1:numel(u)
u(i) = u(i) + h;
yh = f(u);
J(:,i) = (yh-y)/h;
u(i) = u(i) - h;
end
end
See Also
Categories
Find more on Particle & Nuclear Physics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!