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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by