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 (최근 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
Sulaymon Eshkabilov 2020년 9월 8일
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