How can I get the Secant method to repeat ?

Hi everyone , can anyone please show me why my script isn't repeating its calculation? It only calculates the root at theta = 20 and then the loop isn't repeating cheers
clear all
clc
M2=5;
r=1.4;
theta_vec=20:0.1:42;
ciL=35;
cim1L=ciL-1;
fi=((2*cotd(ciL).*((M2.^2).*((sind(ciL)).^2)-1))./((M2.^2).*(r+cosd(2*ciL))+2))-tand(theta_vec);
for n=1:length(theta_vec);
theta=theta_vec(n);
while abs(fi)>1.0e-6;
fi=((2*cotd(ciL).*((M2.^2).*((sind(ciL)).^2)-1))./((M2.^2).*(r+cosd(2*ciL))+2))-tand(theta);
fim1=((2*cotd(cim1L).*((M2.^2).*((sind(cim1L)).^2)-1))./((M2.^2).*(r+cosd(2*cim1L))+2))-tand(theta);
cip1L=ciL-(ciL-cim1L)*fi(n)/(fi-fim1);
cim1L=ciL;
ciL=cip1L;
end
end

 Réponse acceptée

Your code is rather dense. However, I did observe the looping in your code. And... (drum roll please) ...
You've got a bug in your calculation! The for-loop executes 221 times, but the while-loop only executes 4 times and only in the 1st iteration of the for-loop. Have a look at the code I added below and the output produced. This should give you a strong hint on where to look and adjust to set things right. Welcome to debugging. :)
M2=5;
r=1.4;
theta_vec=20:0.1:42;
ciL=35;
cim1L=ciL-1;
fi=((2*cotd(ciL).*((M2.^2).*((sind(ciL)).^2)-1))./((M2.^2).*(r+cosd(2*ciL))+2))-tand(theta_vec);
z=1; % use z to see how many times the while loop executes
for n=1:length(theta_vec)
% I first added a line below to output n. This confirmed that the
% for-loop executes 221 times. Then, I commented out the line.
% n
theta=theta_vec(n);
while abs(fi)>1.0e-6
[n z] % output n and z
z = z+1; % increment z so it increases with each execution of the while-loop
fi=((2*cotd(ciL).*((M2.^2).*((sind(ciL)).^2)-1))./((M2.^2).*(r+cosd(2*ciL))+2))-tand(theta);
fim1=((2*cotd(cim1L).*((M2.^2).*((sind(cim1L)).^2)-1))./((M2.^2).*(r+cosd(2*cim1L))+2))-tand(theta);
cip1L=ciL-(ciL-cim1L)*fi(n)/(fi-fim1);
cim1L=ciL;
ciL=cip1L;
end
end
Output:
ans =
1 1
ans =
1 2
ans =
1 3
ans =
1 4

2 commentaires

Jan
Jan le 6 Mai 2021
Thanks. A good answer.
JiaJun Zeng
JiaJun Zeng le 6 Mai 2021
Thanks so much ! I figured out!!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by