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
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 件のコメント
Sulaymon Eshkabilov
Sulaymon Eshkabilov 2020 年 9 月 8 日
編集済み: Sulaymon Eshkabilov 2020 年 9 月 8 日
It is a pleasure! :) Cheers

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by