Search code examples
graphoctavetrigonometry

How do I plot the graph for differentiation of a function on Octave?


I was trying to learn trigonometry from the beginning. so I can plot a curve by giving these as commands.

x1 = linspace(-2*pi, 2*pi)
y1 = cos(x1)
plot(x1, y1)

But If I try to do this,

x1 = linspace(-2*pi, 2*pi)
y2 = diff(cos(x1))
plot(x1, y1) 

I receive an error stating

error: __plt2vv__: vector lengths must match error: called from     __plt__>__plt2vv__ at line 487 column 5     __plt__>__plt2__ at line 247 column 14     __plt__ at line 112 column 18     plot at line 229 column 10

However, I do get values for y2 = diff(cos(x1)), I can't plot anything because of this error.

Note: I know the differentiation of sin(x) is cos(x) and I can just use cos(x), but can't I do it this way?

Tried diff(cos(90)) I got

ans = \[\](0x0)

Solution

  • diff is one element shorter than its input, because it it the differences [v(2)-v(1), v(3)-v(2), ...].

    You need to do something like y2 = [NaN, diff(cos(x1))]; to pad your array to be the same size as x1.

    Note that of course this causes an offset, you would need a central differencing method instead of a forward difference method (like diff) to keep things well-aligned.