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