Why is my for loop not iterating in the way I want?

4 Ansichten (letzte 30 Tage)
JJH
JJH am 4 Nov. 2018
Bearbeitet: madhan ravi am 4 Nov. 2018
I have a piece of code
clear;
x=2;
expapprox=0;
expapproxarray=zeros(1,12);
for i=0:12
expapprox=expapprox+x^i/factorial(i);
error=abs(expapprox-exp(x))
for j=1:size(expapproxarray)
expapproxarray(j)=error
end
end
plot(expapproxarray)
that compares the exponential function to an approximation of that function using the Taylor series. I want to plot the error found between the two functions for an increasing number of terms in the Taylor expansion. I thought this could be done using the code above but there is a problem with how the second loop works. I think the problem is that the full iteration of the second loop is being done within the first loop but changing the order of the loops gives another wrong answer. How can I get the value of error for each value of I to be outputted into some array that I have called expapproxarray that can then be plotted as a function of i?

Akzeptierte Antwort

Stephen23
Stephen23 am 4 Nov. 2018
Bearbeitet: Stephen23 am 4 Nov. 2018
N = 2; % the value to use.
% Approximation:
X1 = 1:12; % the number of terms.
Y1 = nan(size(X1));
for k = X1
T = 0:k-1;
Y1(k) = sum(N.^T./factorial(T));
end
% Inbuilt function:
X2 = X1([1,end]);
Y2 = exp([N,N]);
% Plot:
plot(X1,Y1,'*',X2,Y2,'-')
xlabel('Number of terms')
ylabel('Output value')
Plots this:
You can plot the error simply by subtracting exp(N):
plot(X1,Y1-exp(N))

Weitere Antworten (1)

madhan ravi
madhan ravi am 4 Nov. 2018
Bearbeitet: madhan ravi am 4 Nov. 2018
x=2;
expapprox=cell(1);
expapprox(1)={0};
expapproxarray=zeros(1,12);
error1=cell(1);
expapproxarray=cell(1);
for i=2:12 %your loop didn't iterate because it should start from 2 because you already defined the first element
expapprox{i}=expapprox{i-1}+x^i/factorial(i);
error1{i}=abs(expapprox{i}-exp(x)); %your second loop as no meaning because 1:1 is still one doesn't mean anything here
end
plot(cell2mat(error),'*') %plot function plots the function according to the index so this represents I vs error
hold on
plot(cell2mat(expapprox)) %this represents i vs expapprox
  1 Kommentar
madhan ravi
madhan ravi am 4 Nov. 2018
plus I also suspect
error1{i}=abs(expapprox{i}-exp(x));
should be
error1{i}=(expapprox{i}-exp(x));
because the abs function would simply ignore the negative values which is not what we want right?

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by