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('======= ======= ======= ======');
%f = fun(t);
%hold on
%grid on
while f(x) > epsilon
x = (a*f(b) - b*f(a))/(f(b)-f(a));
if f(a)*f(x)< 0
a = x;
f(a) = f(x);
elseif f(a)*f(x)> 0
b = x;
f(b) = f(x);

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