Conversion to logical from sym not possible

조회 수: 17 (최근 30일)
Gyp
Gyp 2020년 2월 4일
댓글: Walter Roberson 2020년 2월 7일
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

답변 (2개)

Nikhil Sonavane
Nikhil Sonavane 2020년 2월 7일
편집: Nikhil Sonavane 2020년 2월 7일
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
Nikhil Sonavane
Nikhil Sonavane 2020년 2월 7일
Yes, that’s why sym isn’t used in the code
Walter Roberson
Walter Roberson 2020년 2월 7일
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.

댓글을 달려면 로그인하십시오.


Walter Roberson
Walter Roberson 2020년 2월 7일
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
  댓글 수: 1
Walter Roberson
Walter Roberson 2020년 2월 7일
You can also use coeffs() to test for higher order powers.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Calculus에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by