plotting graph with 2 different size of vector

1 visualizzazione (ultimi 30 giorni)
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

Risposta accettata

Davide Masiello
Davide Masiello il 8 Nov 2022
Modificato: Davide Masiello il 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.

Più risposte (0)

Categorie

Scopri di più su Graph and Network Algorithms in Help Center e File Exchange

Tag

Prodotti


Release

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by