Trying to get taylor's series to work the old fashion way for x^2." Array indices must be positive integers or logical values"?
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Kevin Zhou
am 8 Sep. 2020
Bearbeitet: Sulaymon Eshkabilov
am 8 Sep. 2020
%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))
0 Kommentare
Akzeptierte Antwort
Sulaymon Eshkabilov
am 8 Sep. 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 Kommentare
Sulaymon Eshkabilov
am 8 Sep. 2020
Bearbeitet: Sulaymon Eshkabilov
am 8 Sep. 2020
It is a pleasure! :) Cheers
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!