Conversion to logical from sym not possible

19 views (last 30 days)
Gyp
Gyp on 4 Feb 2020
Commented: Walter Roberson on 7 Feb 2020
Error: Conversion to logical from sym is not possible.
Error while diff(fun)<0
Objective: Creating a program that calculates the derivative for any polynomial entered by a user and that user receives all the derivatives until it reaches zero.
---------------------------------
clc
clear
syms x;
fun=input('Enter polynomial expresssion: \n');
pretty(fun)
i=0;
while diff(fun)<0
diff(f,i)
disp(diff(f,i))
i=i+1;
end

Answers (2)

Nikhil Sonavane
Nikhil Sonavane on 7 Feb 2020
Edited: Nikhil Sonavane on 7 Feb 2020
In your code diff(fun) never reaches less than 0, hence the loop isn't executed. Also, you are comapring a symbolic variable with a numeric value which is not possible Moreover, in the loop everytime you are calculating differentiation of the same function and not the derivative of the previous computed derivative. You may try the following code-
fun=input('Enter polynomial expresssion: \n');
pretty(fun)
i=0;
fund=diff(fun,x);
disp(fund);
while fund~=0
fund=diff(fund,x);
disp(fund);
i=i+1;
end
i
You may refer to the documentation of diff for more details about the function.
  3 Comments
Nikhil Sonavane
Nikhil Sonavane on 7 Feb 2020
Yes, that’s why sym isn’t used in the code
Walter Roberson
Walter Roberson on 7 Feb 2020
In that case, x is undefined.
What is your expectation for how the user will enter the polynomial expression? If x is numeric then if the user enters a formula in x in response to the input() request, then the result would be a scalar numeric value. If x is numeric, then diff(fun,x) is invalid unless x happens to be a scalar integer.

Sign in to comment.


Walter Roberson
Walter Roberson on 7 Feb 2020
You are taking diff() of a symbolic expression, which is the calculus differentiation operation. The result would generally be a formula in x rather than a numeric value. You then try to test whether the formula is less than 0, but as long as the formula has a symbolic variable remaining, you cannot tell whether it is less than 0 because the symbolic variable could be any value including complex.
If you want to keep iterating until there are no more symbolic variables, you can test whether symvar() of the expression is empty. Also remember to update the variable or else you will have an infinite loop

Community Treasure Hunt

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

Start Hunting!