Conversion to logical from sym not possible

20 ビュー (過去 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 Center および File ExchangeAssumptions についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by