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

조회 수: 5 (최근 30일)
JJH
JJH 2018년 11월 4일
편집: madhan ravi 2018년 11월 4일
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?

채택된 답변

Stephen23
Stephen23 2018년 11월 4일
편집: Stephen23 2018년 11월 4일
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))

추가 답변 (1개)

madhan ravi
madhan ravi 2018년 11월 4일
편집: madhan ravi 2018년 11월 4일
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
madhan ravi
madhan ravi 2018년 11월 4일
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?

댓글을 달려면 로그인하십시오.

카테고리

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