3

I am trying to plot a function and its derivative using fplot.

fplot('3*x*sin(x) - 2*x', [-2*pi 2*pi], 'r')

This is working, But the command below is showing error.

fplot('diff(3*x*sin(x) - 2*x)', [-2*pi 2*pi], 'g')

Error Shown

??? Subscripted assignment dimension mismatch.

Error in ==> fplot at 105
x = xmin+minstep; y(2,:) = feval(fun,x,args{4:end});

Please give me some suggestions?

3
  • What error is it showing ? Commented Jan 16, 2013 at 18:34
  • Try plotting the second plot in a new plot to see if it works. Commented Jan 16, 2013 at 18:48
  • @Pavan Ok, But what is the reason for that error. d = diff(3*x*sin(x)-2*x) gives the derivative of that function. fplot('d', [-2*pi 2*pi], 'g') gives a wrong plot Commented Jan 16, 2013 at 18:55

2 Answers 2

4

The problem is including diff in the function string. Your function needs to produce N outputs for N inputs, but having diff give N-1 outputs. From the documentation on fplot (emphasis added):

The function must be of the form y = f(x), where x is a vector whose range specifies the limits, and y is a vector the same size as x and contains the function's value at the points in x (see the first example).

zplesivcak's answer shows one way to work around this limitation. You could also evaluate the function non-symbolically:

x = linspace(-2*pi, 2*pi, 1000);
y = diff(3*x.*sin(x) - 2*x);
figure
plot(y)
Sign up to request clarification or add additional context in comments.

1 Comment

@shoelzer Thanks, But I was exploring the ``fplot` function.
1

You could first calculate derivative, transform result in a string, and then plot obtained function:

syms x;
di = char( diff(3*x*sin(x)-2*x) );
fplot(di, [-2*pi 2*pi], 'g');

Edit: @shoelzer provides correct explanation for the error you've received.

1 Comment

@zplesivcak, Thank you for your fast reply

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.