Help with loop error
1 回表示 (過去 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!