Trying to get taylor's series to work the old fashion way for x^2." Array indices must be positive integers or logical values"?

2 次查看(过去 30 天)
%problem 1_a
clear all
%decrement value loop
%h = x-x0
h=-0.8:0.01:1;
tic %start a timer for the i loop below
for i=0.01:length(h) % do something on x(i)
fxx(i,0)=h(i)^2;
fxhn1(i,0)=0;
fxhn2(i,0)=h(i)^2;
fxhn3(i,0)=h(i)^2;
end
tloop=toc %stop the timer for the i loop above and store the result
plot(h,fxx,h,fxhn1,h,fxhn2,h,fxhn3,'linewidth',2)
legend('x^2','f(x+h) n=1','f(x+h) n=2','f(x+h) n=3')
title('Taylor Approximation of x^2 About x=0')
xlabel('h')
ylabel('f(0+h)')
%seperate code
display('Average Absolute Deviation of 1st Order Approx')
mean(abs(fxx-fxhn1))
display('Average Absolute Deviation of 2nd Order Approx')
mean(abs(fxx-fxhn2))
display('Average Absolute Deviation of 3rd Order Approx')
mean(abs(fxx-fxhn3))

采纳的回答

Sulaymon Eshkabilov
Hi,
Here are corrected part of the code with for loop:
tic %start a timer for the i loop below
for i=1:length(h) % do something on x(i)
fxx(i)=h(i)^2;
fxhn1(i)=0;
fxhn2(i)=h(i)^2;
fxhn3(i)=h(i)^2;
end
tloop=toc %stop the timer for the i loop above and store the result
If there is no requirement to use for loop, then it is more reasonable to use vectorization instead, e.g.:
tic %start the timer
fxx=h.^2;
fxhn1=zeros(size(h));
fxhn2=h.^2;
fxhn3=h.^2;
tvec=toc % Stop the timer
  3 个评论

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by