Help with loop error

조회 수: 2 (최근 30일)
amateurintraining
amateurintraining 2017년 10월 13일
댓글: James Tursa 2017년 10월 14일
My function is as follows but keeps coming up with the error that the output argument "approx" is not assigned. How do I change it to produce the desired outputs?
function [ exact, approx, abs_error, terms ] = calcTaylorTerms( x, dx, tol, max_terms, exp_or_sin )
%CALCTAYLORTERMS
% x: is x
% dx: delta x
% tol: the error tolerance to be met
% max_terms: the maximum number of terms to include before giving up
% exp_or_sin: a flag that determines whether f(x)=e^x or f(x)=sin(x)
% exact: analytical solution to f(x+deltax)
% approx: the Taylor series approximation of f(x+deltax)
% abs_error: the absolute value of the difference between the exact
% solution and the Taylor series approximation
% terms: the number of terms ultimately used in the Taylor series
if isequal(exp_or_sin,"exp")||isequal(exp_or_sin,"sin")
if isequal(exp_or_sin,"exp")
exp_or_sin=exp(x);
elseif isequal(exp_or_sin,"sin")
exp_or_sin=sin(x);
end
abs_error=0;
n=1;
count=0;
terms=1;
while abs_error>=tol && n>1 && terms>max_terms
count=count+1;
terms(count)=exp_or_sin+(1)^(count+1)*(dx^n).*diff(exp_or_sin,x,n)/factorial(n);
approx(count)=sum(terms);
n=n+1;
exact=exp_or_sin(x+dx);
abs_error=abs((exact-approx)/exact);
end
exact=exp_or_sin(x+dx);
approx=approx;
abs_error=abs_error
X=terms;
X(:)=1;
terms=sum(X)
else
exact=NaN;
approx=NaN;
abs_error=NaN;
terms=NaN;
end
end

답변 (1개)

James Tursa
James Tursa 2017년 10월 13일
편집: James Tursa 2017년 10월 13일
Maybe move all of the default stuff prior to your if test. E.g.,
exact = NaN;
approx = NaN;
abs_error = NaN;
terms = NaN;
if isequal(exp_or_sin,"exp")||isequal(exp_or_sin,"sin")
:
etc
  댓글 수: 2
amateurintraining
amateurintraining 2017년 10월 13일
Unfortunately, if I do that it just produces approx=NaN, which means that the variable is still not defined. How do I call a variable out of a while-loop?
James Tursa
James Tursa 2017년 10월 14일
If it is coming back as NaN, that gives you a clue. Namely, that these values were not set inside the while loop. Use the debugger to step through your code and figure out why you are not getting inside that while loop.

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

카테고리

Help CenterFile Exchange에서 Configure Simulation Conditions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by