MATLAB: How does one solve the roots of a symbolic polynomial in a loop

symbolic polynomialsymbolic rootssyms with loops

Hello,
I am attempting to fit data that involves solving a fifth order polynomial for the real positive root. I need to calculate the real positive root over a set of values, so I was trying to use syms with a loop in order to get the root with each iteration of the symbolic polynomial. It should have five roots, though I just need one. I'm not very good at using syms so I am likely confusing some syntax. It tells me the error "Conversion to logical from sym is not possible". I imagine this is because MatLab thinks I am still using a symbolic variable when doing the logic check, which it doesn't understand. Though I thought my program has converted back to numerical at that point. Does anyone know a good way to do this?
Thank you.
syms X Y
for i = 1:length(injections)
Y = C1(i,1).*X + C2.*X + C3(i,1).*X +
C4(i,1).*X^2 + C5.*X^2 + C6(i,1).*X^2 + C7(i,1).*X^3 +
C8.*X^3 + C9(i,1).*X^3 + C10(i,1).*X^4 + C11.*X^4 +
C12(i,1).*X^4 + C13.*X^5;
realposans(:,i) = solve(Y == 0,'Real',true);
for j = 1:size(realposans,1)
if realposans(j,i) > 0
LF(i,1) = realposans(j,i);
end
end
end

Best Answer

Maybe I’m missing something, but wouldn’t it be easier to cast your equation as:
K5*x^5 + K4*x^4 + K3*X^3 + K2*x^2 + K1*x + (K0-Y)
with:
K5 = C13(i,1), K4 = (C10(i,1) + C11(i,1) + C12(i,1)), K3 = ... etc.
then use roots as:
K5 = 6;
K4 = 5;
K3 = 4;
K2 = 3;
K1 = 2;
K0 = 1;
r = roots([K5 K4 K3 K2 K1 K0]);
rr = r(imag(r) == 0)
Loop with values of C1 ... C13, assign rr(i) with the loop index, and avoid the Symbolic Math Toolbox entirely. The Symbolic Toolbox has its strengths, but looping to solve equations such as yours is not one of them.