"Subscript indices must either be real positive integers or logicals" error from regula falsi function

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

2 Commenti

How are you calling the function?
This error often implies that Matlab sees 'fun' as being a matrix to index into rather than a function. One of the joys of Matlab using the same syntax for function calls and for array indexing.
In this case it is probably 'b' that it has a problem with, at a guess, as an index into f.
I am calling the fun as:
fun = 0;
fun = @(in)(in^.2-5);
and as for the falsi function I am just calling it as:
falsi(fun,a,b,epsilon);

Accedi per commentare.

 Risposta accettata

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

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by