MATLAB: “Subscript indices must either be real positive integers or logicals” error from regula falsi function

errorfalse pointregula falsisubscript indices

Hello All,
I am need in need of some help with creating this regula falsi function. Below is the function I have created along with the definitions for the variables in the function, however when trying to run in the command prompt, I get the error "Subscript indices must either be real positive integers or logicals" and points to the line with f(b) = fun(b). I don't really understand what this error means and what exactly its looking at.
FYI, I am new to matlab, so any help would be much appreciated.
Thank you.
fun = @(in)(in^.2 - 5); %defined in the command window
function [ x ] = falsi(fun,a,b,epsilon) %functions I created
disp(' I a b x');
disp('======= ======= ======= ======');
k=0;
f(a)=fun(a);
f(b)=fun(b);
%t=linspace(b,a,100);
%f = fun(t);
%plot(t,f);
%hold on
%set(fig,'color','white')
%grid on
while f(x) > epsilon
k=k+1;
x = (a*f(b) - b*f(a))/(f(b)-f(a));
f(x)=fun(x);
fprintf('%5i,%11.4f;%11.4f,%11.4f\n',k,a,b,x);
if f(a)*f(x)< 0
a = x;
f(a) = f(x);
elseif f(a)*f(x)> 0
b = x;
f(b) = f(x);
else
break
end
end

Best Answer

  • I don't understand what you're trying to do with the statements f(b) = fun(b) and similar. This assigns the result of fun at value b to the element at index b of matrix (or vector) f. Of course, since indices must be positive integers you get an error if b is not.
    As said, I don't understand why you're trying to store these values at arbirtrary indices of a matrix. Two possible ways to fix your code:
    • replace all instances of f(a) by f(1), f(b) by f(2) and f(x) by f(3). The values will be stored in a 3 element vector
    • replace all instances of f(a) by fa, f(b) by fb and f(x) by fx. The values will be stored in individual variables