MATLAB: Having a problem troubleshooting code (relatively simple code)

debugging

Running a relatively simple code to plot 2 variables against each other.
clear;clc;
syms A1 B2 SWR
R=0.5;
Cp=0.5;
Cv=0.3;
R = Cv^2*((1/Cv-tan(A1))^2 - (tan(B2))^2)/2/(1-Cv*tan(A1) - Cv*tan(B2)); %%Eq 1
Cp = 1 - (tan(B2)/(1/Cv - tan(A1)))^2; %%Eq2
i = 1;
while Cv<101
i = i + 1;
Cv= Cv + 0.01;
[A1,B2] = vpasolve([R, Cp], [A1,B2]); %%Solving Eq1 and Eq2 simultaneously for A1 and B2
SWR = 1 - Cv*(tan(A1) + tan(B2)); %%using A1 and B2 to solve for SWR
X(i,2) = Cv;
Y(i,2) = SWR;
end
plot(X(:,2),Y(:,2),'g-');
hold on
My end goal here is to plot Cv on the X axis and SWR on the Y axis. But for some reason, it seems to be entering into some sort of infinite loop somewhere since its taking way too long to give an output or even an error. I have tried debugging it but I still am not able to find where the problem is occurring.

Best Answer

The Symbolic Math Toolbox is not the best way to solve iterative problems.
I coded your equations as anonymous functions and gave them to the Optimization Toolbox fsolve function that works best for problems like these. It works, but the ‘SWR’ value is negative (and since I believe that stands for ‘standing wave ratio’ on a transmission line, absolutely does not make sense, at least in that context).
Look over your equations to be sure they are set up correctly:
Cp=0.5;
% Cv=0.3;
Cvv = [0.3:0.1:101];
R = @(A1,B2,Cv) Cv.^2.*((1./Cv-tan(A1)).^2 - (tan(B2)).^2)./2./(1-Cv.*tan(A1) - Cv.*tan(B2)); %%Eq 1
Cp = @(A1,B2,Cv) 1 - (tan(B2)./(1./Cv - tan(A1))).^2; %%Eq2
% MAPPING: A1 = p(1), B2 = p(2)
Eqn = @(p,Cv) [R(p(1),p(2),Cv), Cp(p(1),p(2),Cv)];
for k1 = 1:length(Cvv)
Cv = Cvv(k1);
[P(:,k1),Fval] = fsolve(@(p)Eqn(p,Cv), [-145; 23]);
SWR(k1) = 1 - Cv*(tan(P(1,k1)) + tan(P(2,k1)));
end
figure(1)
plot(Cvv, SWR)
grid
xlabel('C_v')
ylabel('SWR')
I did the symbolic solution first with the initial value of ‘Cv’ (0.3), and used that solution ‘[-145,23]’ for the initial estimates in my loop. If you believe they should be other values, change them, run the loop, and see what works best. Since your equations are periodic, the ‘correct’ initial parameter estimates are important.