How can I get the Secant method to repeat ?

1 view (last 30 days)
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

Accepted Answer

Scott MacKenzie
Scott MacKenzie on 6 May 2021
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

More Answers (0)

Categories

Find more on Loops and Conditional Statements 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!