Azzera filtri
Azzera filtri

Help with loop error

2 visualizzazioni (ultimi 30 giorni)
amateurintraining
amateurintraining il 13 Ott 2017
Commentato: James Tursa il 14 Ott 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

Risposte (1)

James Tursa
James Tursa il 13 Ott 2017
Modificato: James Tursa il 13 Ott 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 Commenti
amateurintraining
amateurintraining il 13 Ott 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 il 14 Ott 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.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by