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

10 次查看(过去 30 天)
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

回答(2 个)

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

Cris LaPierre
Cris LaPierre 2022-9-6
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 个评论
Cris LaPierre
Cris LaPierre 2022-9-6
编辑:Cris LaPierre 2022-9-6
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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by