Output argument ‹variable› (and maybe others) not assigned during call to ‹function›
Show older comments
Please help! I keep getting this error for k
Function:
Function [r, k] = RegulaFalsi_Mod(f, a, b, kmax, tol)
%
%
% [r, k] = RegulaFalsi_Mod(f, a, b, kmax, tol), where
%
% f is an anonymous function representing f(x),
% a and b are the limits of the interval [a,b],
% kmax is the maximum number of iterations (default 20),
% tol is the scalar tolerance for convergence (default 1e-4),
%
% r is the approximate root of f(x) = 0,
% k is the number of iterations needed for convergence.
%
if nargin < 5 || isempty(tol), tol = 1e-4; end
if nargin < 4 || isempty(kmax), kmax = 20; end
if f(a)*f(b) > 0
r = 'failure';
return
end
ri = 0; le = 0; m = 0; n = 0;
c = zeros(1, kmax); % Pre-allocate
disp(' k a b')
for k = 1:kmax,
if ri > 0 && mod(ri,4) == 0 % Left end moved 3 consecutive times
m = m + 1;
elseif le > 0 && mod(le,4) == 0 % Right end moved 3 consecutive times
n = n + 1;
end
f_a = f(a)/2^n; f_b = f(b)/2^m;
c(k) = (a*f_b - b*f_a)/(f_b - f_a); % Find the x-intercept
if f(c(k)) == 0, % Stop if a root has been found
r = c(k);
return
end
fprintf('%2i %11.6f%11.6f\n',k,a,b)
if f_b*f(c(k)) > 0 % Check sign changes
b = c(k); % Adjust the right endpoint
m = 0; % Reset m since the right end moved
le = le + 1; ri = 0; % Increase left count, reset right
else
a = c(k); % Adjust the left endpoint
n = 0; % Reset n since the left end moved
ri = ri + 1; le = 0; % Increase right count, reset left
end
if length(unique(c)) > 2
if abs(c(k)-c(k-1)) < tol, % Stop if tolerance is met
r = c(k);
return
end
end
end
Answers (1)
Star Strider
on 3 Sep 2020
I cannot run your code because I have no idea what the arguments should be. I guessed at the arguments, and when I ran your function reproduced the behaviour you reported.
The problem appears to be here:
if f(a)*f(b) > 0
r = 'failure';
return
end
Probably the easiest way to avoid that problem is to have the first two executable lines in your function (before the first nargin check) be:
r = NaN;
k = NaN;
Those will be overwriten once your script executes beyond that point.
Meanwhile, review the logic in that specific if block to see if it is what you actually want to do.
Categories
Find more on Word games in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!