Help with loop error
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(1 个)
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 个评论
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 Center 和 File Exchange 中查找有关 Configure Simulation Conditions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!