calculate derivative of a function using handle

Hi, Matlab community
I have two scripts, one is
syms f(x)
f=@(x)func(x);
df=diff(f,x);
fplot(@(x) df(x),[0 10])
the other one is
function f=func(x)
if x >= 1 && x <= 2;
f=-x*1/4+2;
else
f=0;
end
And the error shows like:
Conversion to logical from sym is not possible.
How to solve ths problem?
Thank you for your attention

2 Comments

How did you use those functions...show us the full code.
thank you for your quick answer.
I put them in the same folder and ran demo.m.

Sign in to comment.

Answers (2)

You need to take the derivative of the original function and then apply the limits
syms x
f(x) = (-x*1/4+2);
df(x) = diff(f,x).*(1<=x&x<=2);
fplot(df,[0 10])

7 Comments

Thank you for your answer. Error shown again shows Error using sum/subindex.
Can you paste complete error message?
sure. demo
Error using sym/subsindex (line 663)
Invalid indexing or function definition. When defining a function, ensure that the body of the
function is a SYM object. When indexing, the input must be numeric, logical or ':'.
Error in demo (line 2)
f(x)=(-x*1/4+2);
Try your code again after running
clear f x
Thank you for advice. However, it shows
Error using sym/min (line 86)
Input arguments must be convertible to floating-point numbers.
Error in fplot (line 116)
ymin = min(y(J)); ymax = max(y(J));
Error in demo (line 5)
fplot(df,[0 10])
Not sure about the issue. I don't have R2014a. Maybe this will work
fplot(matlabFunction(df),[0 10])
In R2014a, fplot() was not yet able to plot symbolic expressions.

Sign in to comment.

function f=func(x)
f = piecewise(x >= 1 && x <= 2, -x*1/4+2, 0);

3 Comments

Thank you for your answer. Piece wise is a function introduced after Matlab 2016. Is there a syntax to do it on the version earlier than 2016?
Mine is 2014a and Thank you for your attention.
function f=func(x)
syms t
temp(t) = feval(symengine, 'piecewise', '([t >= 1 and t <= 2, -t*1/4+2], [Otherwise, 0])');
f = temp(x);

Sign in to comment.

Products

Release

R2014a

Tags

Asked:

on 8 Jun 2020

Commented:

on 9 Jun 2020

Community Treasure Hunt

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

Start Hunting!