plotting graph with 2 different size of vector

2 vues (au cours des 30 derniers jours)
MANANJAYA NAYAK
MANANJAYA NAYAK le 8 Nov 2022
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

Réponse acceptée

Davide Masiello
Davide Masiello le 8 Nov 2022
Modifié(e) : Davide Masiello le 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.

Plus de réponses (0)

Catégories

En savoir plus sur Graph and Network Algorithms dans Help Center et File Exchange

Tags

Produits


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by