plotting graph with 2 different size of vector
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Davide Masiello
2022-11-8
编辑:Davide Masiello
2022-11-8
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.
0 个评论
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!