trying to call a function from a function file in a script file

67 次查看(过去 30 天)
此 个问题 已被 Stephen23 标记
  1 个评论
Stephen23
Stephen23 2024-7-23,3:37
编辑:Stephen23 2024-7-23,3:57
"but when I try to run this code the error says "Execution of script afunction as a function is not supported"
Get rid of all code outside of the function definition. Having code outside of the function definition makes it into a script, which will not work. You need to provide FZERO with a function handle, not run a script or call a function:
Do not call your function. Provide FZERO with a function handle:
x = fzero(@afunction, [llim ulim],options);

请先登录,再进行评论。

回答(2 个)

Muskan
Muskan 2024-7-23,3:12
编辑:Muskan 2024-7-23,3:45
Hi,
As per my undersatnding the issue is because you named the script "afunction"
Hence when when the script gets to this line:
func = afunction;
As a result, it tries to call "afunction" but cannot, because that is what you called your script.
The way to resolve this issue is to change the name of your script to something else.
  3 个评论
Muskan
Muskan 2024-7-23,3:17
Is it possible for you to share the script in order to help debug?
Stephen23
Stephen23 2024-7-23,3:51
Get rid of all code outside of the function definition! This you should save in an MFILE of the same name:
function y = afunciton(x)
y = exp(cos(x)) - x.^3 + 2*x.^2 + 5*x - 3;
end
And this is how you call it:
llim = -5;
ulim = -1;
options = optimset('Display','iter','TolX',10^-7,'Maxiter',500);
x = fzero(@afunciton, [llim ulim],options)
Func-count x f(x) Procedure 2 -1 -3.28347 initial 3 -1.08663 -3.1958 interpolation 4 -1.08663 -3.1958 bisection 5 -1.28168 -2.68766 interpolation 6 -1.28168 -2.68766 interpolation 7 -1.53453 -1.31264 interpolation 8 -1.73932 0.461266 interpolation 9 -1.68607 -0.0601463 interpolation 10 -1.69221 -0.00220062 interpolation 11 -1.69244 7.41169e-07 interpolation 12 -1.69244 7.41169e-07 interpolation Zero found in the interval [-5, -1]
x = -1.6924

请先登录,再进行评论。


Walter Roberson
Walter Roberson 2024-7-23,3:21
func = @afunction; %trying to make the variable func equivalent to "afunciton",
% the function I created in the afunction file but it doesn't work :(
llim = -5;
ulim = -1;
options = optimset('Display','iter','TolX',10^-7,'Maxiter',500);
[x] = fzero(func, [llim ulim],options);
However... your afunction is a script rather than a function, and for the purposes of fzero you strictly need to use a function.
My guess is that your afunction.m starts something like
clear all; clc
function z = afunction(x)
That "clear all" at the beginning of it is unnecessary, and makes the code into a script file instead of a function file.

类别

Help CenterFile Exchange 中查找有关 R Language 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by