plotting graph with 2 different size of vector

1 view (last 30 days)
Plot the function f(x)=sin (2x) & its derivative d/dx sin(2x)on the same graph.
x=1:10;
y1=sin(2*x);
y2=diff(sin(2*x)); % i want calulated directly by diff command
plot(x,y1,x,y2)
% showing error vector must be same length

Accepted Answer

Davide Masiello
Davide Masiello on 8 Nov 2022
Edited: Davide Masiello on 8 Nov 2022
Applying diff to a Nx1 array produces an (N-1)x1 array, hence your problem.
In truth, you are not really calculating the derivative of the array, because the function diff only calculates the difference of each successive pair of elements. You must divide that by if you wish to compute the derivative.
Still, the derivative array will have one less element than the original vector, so you can plot it only vs x(1:end-1)(depending on how you define the differencing scheme).
See the example below for reference
x=1:10;
y1=sin(2*x);
y2=diff(y1)./diff(x);
plot(x,y1,x(1:end-1),y2)
legend('function','derivative')
Now, if the derivative must have the same number of elements of the original array, some more sophisticated techniques can be applied, but that would be a whole different subject.

More Answers (0)

Categories

Find more on Graph and Network Algorithms in Help Center and File Exchange

Tags

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!