Differentiation question using diff and polyder
4 次查看(过去 30 天)
显示 更早的评论
I already wrote my code, I just need help figuring out a couple of errors.
So my function has 3 parts. For the first part, I want to crete a function that finds the derivative of ln x. I want to set x = 2:0.05:4. In the function MyDierentiation, I want to compute the approximated values of derivatives at x by using the MATLAB function diff, and assign the value to df1
function [df1, df2] = MyDifferentiation()
%%Part A
x = 2:0.05:4
y= log(x)
df1= diff(x)
I am getting an error in my code. My instructor told me that if f'(x) is a 1x21 array, df1 will be a 1x20 array. So, i'm guessing I have to make df1 have the same length as x by assuming that the last point has the same derivative as the preceding point? Is that right? how would I go about doing this on MATLAB?
%%Part B
x = 2:0.05:4
y=log(x)
df2= polyfit(x,y)
df2=polyder(x)
I also compute the approximated derivative using the function polyder (By using the same x = 2:0.05:4 and computing the corresponding y values of the function y = ln(x).) I also wan to fit the x and y data by a 3rd order polynomial. The values of the derivative at x will be assigned to df2.
%%Part C
hold on
plot (df1)
plot (df2)
hold off
ylabel('derivative')
xlabel('x')
legend('diff','polyder','exact values')
lines = {'diff','polyder','exact values'}
legend(lines)
I haven't tested this code because of the errors above, but hopefully it's plot the right graph once the errors are fixed. ( I wanted to plot df1, df2, and the exact values of the derivative in a single plot. Please note that I am using a blue solid line for df1, red dashed line for df2, and green dotted line for exact values. I am also setting LineWidth to 2 and providing a legend to the graph. )
thank you everyone!
0 个评论
采纳的回答
Star Strider
2012-10-26
编辑:Star Strider
2012-10-26
Problems like this are in a sense a bit artful because you have options. I suggest:
% % Part A:
Don't you actually want to calculate:
df1 = diff(y);
instead?
In that situation, I suggest perhaps plotting df1 as:
plot(x(1:length(df1)), df1)
% % Part B:
If you want to calculate a 3rd order polynomial fit, I suggest:
df2 = polyfit(x,y,3);
4 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Discrete Data Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!