Facing difficulty in finding the error saying Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched delimiters."

9 Ansichten (letzte 30 Tage)
Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched delimiters." here is the code. can't find where the mistake is. Need help.
function f=secant(xi)
f = x(i)^6-x(i)-1;
%f = @(x) x(i)^6-x(i)-1;
x(1)=2;
x(2)=1;
e=10^-3;
n=50;
for i=1:n-2
x(i+2)=x(i+1)-(f(x(i+1))*(x(i+1)-x(i)))/(f(x(i+1))-f(x(i)));
fprintf('x%d=%.10f\n',i,x(3))
if abs(x(3)-x(2))<e
break
end
x(i)=x(i+1);
x(i+1)=x(i+2);
end
plot(x(i),f(x(i)),'b')
disp([i x(i) f(x(i)) abs(x(i)-x(i+1))])
end

Antworten (2)

Torsten
Torsten am 6 Sep. 2022
f = @(x)x.^6-x-1
instead of
f = x(i)^6-x(i)-1;

Cris LaPierre
Cris LaPierre am 6 Sep. 2022
You are trying to index a function input variable in the function declaration. This is not allowed. Instead, create a new variable name in the function declaraion,
function f = secant(xIn)
and when calling your function, index you input variable.
out = secant(x(i))
To make this change, you will likely have to update how you use x inside your function.
  1 Kommentar
Cris LaPierre
Cris LaPierre am 6 Sep. 2022
Bearbeitet: Cris LaPierre am 6 Sep. 2022
You have updated your problem description. Your original description gave the function declaration and code as pasted below, which does give the error message you provided.
% calling syntax (I added this to recreate the error message)
x = rand(1,5);
out = secant(x)
% original function code
function f=secant(x(i))
Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched delimiters.
f = x(i)^6-x(i)-1;
x(1)=2;
x(2)=1;
e=10^-3;
n=50
for i=1:n-2
x(i+2)=x(i+1)-(f(x(i+1))*(x(i+1)-x(i)))/(f(x(i+1))-f(x(i)));
fprintf('x%d=%.10f\n',i,x(3))
if abs(x(3)-x(2))<e
break
end
x(i)=x(i+1);
x(i+1)=x(i+2);
end
plot(x(i),f(x(i)),'b')
disp([i x(i) f(x(i)) abs(x(i)-x(i+1))])
end

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by