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

1 visualización (últimos 30 días)
%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))

Respuesta aceptada

Sulaymon Eshkabilov
Sulaymon Eshkabilov el 8 de Sept. de 2020
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 comentarios

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by