Error: Conversion to logical from sym is not possible

1 visualización (últimos 30 días)
Delia Bosshart
Delia Bosshart el 25 de Mayo de 2021
Respondida: MULI el 26 de Mayo de 2024
Hello there. I get the following error for my code: "Conversion to logical from sym is not possible".
I need the if statement due to the root in my equation: if my d gets negativ, it can't solve the equation anymore. that is why i would like to have the following condition that in case of a negativ number it will put d equal to zero.
How can I include if statements in a solver (so having values that are saved as syms)? I need the solver function because the real equation is way more complex but having a root.
Also how can I export the solution to a excel file? I don't understand as the solution is still saved as sym. is there the possibility to convert a sym to a double in the end of the code?
syms x
a = 30
b = 20
c = 10
if d > 0
d = (x-c).*2
else d = 0
end
eqn = a + b - 200.*x - d^0.5 == 0
sol_x = vpasolve(eqn, x)

Respuestas (1)

MULI
MULI el 26 de Mayo de 2024
Hi Delia,
I understand that you are getting an error since symbolic variable is compared to a numeric value. To resolve this issue, you may follow these steps.
  • Define `a`, `b`, and `c` are defined as numeric values. This ensures that these parameters are treated as ordinary numbers rather than symbolic variables.
  • Define the equation is defined as an anonymous function `eqn` of `x` and solve it
  • The `fzero` function is employed to find a numerical solution `sol_x` for the equation `eqn`.
  • These modifications transform the original symbolic approach into a numerical one, effectively addressing the conversion error.
Below attached code incorporates above suggestions and solves the value.
% Define parameters
a = 30;
b = 20;
c = 10;
% Define the equation as an anonymous function
eqn = @(x) a + b - 200 * x - sqrt(compute_d(x, c));
% Solve equation numerically
sol_x = fzero(eqn, 0);
% Display solution
disp(['Solution for x: ', num2str(sol_x)]);
% Export the solution to an Excel file
filename = 'solution.xlsx';
xlswrite(filename, sol_x); % Write the solution directly
% Define the function to compute d
function d = compute_d(x, c)
if x > c
d = (x - c) * 2;
else
d = 0;
end
end
You may refer these below documentation links more information on ‘fzero’ function

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by