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
댓글 수: 0
답변 (2개)
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
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))
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 Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!