Help with loop error

1 vue (au cours des 30 derniers jours)
amateurintraining
amateurintraining le 13 Oct 2017
Commenté : James Tursa le 14 Oct 2017
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

Réponses (1)

James Tursa
James Tursa le 13 Oct 2017
Modifié(e) : James Tursa le 13 Oct 2017
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 commentaires
amateurintraining
amateurintraining le 13 Oct 2017
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 le 14 Oct 2017
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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by