【问题标题】:Error using fzero for f=(x.^3).*cos(x) in a loop在循环中对 f=(x.^3).*cos(x) 使用 fzero 时出错
【发布时间】:2018-01-31 18:55:50
【问题描述】:

我尝试使用 fzero 在 -6pi 和 6pi 之间找到函数 f=(x^3)*cos(x) 的所有根。

我创建一个函数:

function y3=f(x)
  f=(x^3)*cos(x);
end

% Then at the command window:

syms x;
fun=@f
x1=-6*pi;
x2=-5*pi;
r=zeros(1,12);
for i=1:12
  x=fzero(@fun,[x1 x2]);
  r(i)=x;
  x1=x1+pi;
  x2=x2+pi;
end

我收到了这个错误:

Error: "fun" was previously used as a variable, conflicting with its use here as the name of a function
or command. See "How MATLAB Recognizes Command Syntax" in the MATLAB documentation for details.

我该如何解决?谢谢

【问题讨论】:

  • 你的函数体应该是y3=(x^3)*cos(x);而不是f=(x^3)*cos(x);
  • 你写fun=@f,后来写@fun。在第二条语句中,您将fun 视为一个函数,但它在您的第一条语句中声明为变量。解决办法是写fzero(fun,...)fzero(@f,...)

标签: matlab function for-loop function-parameter


【解决方案1】:

我想我有一个答案。根据fun 输入到fzero 上的fzero 文档,可以直接输入匿名函数。因此,您可以执行以下操作:

clc; clear;

x1=-6*pi;
x2=-5*pi;

r=zeros(1,12);

for i=1:12
    x=fzero(@(x) (x.^3)*cos(x),[x1 x2]);

    r(i)=x;

    x1=x1+pi;    
    x2=x2+pi;    
end
r

这给出了以下输出:

r =

-17.2788  -14.1372  -10.9956   -7.8540   -4.7124         0         0    4.7124    7.8540   10.9956   14.1372   17.2788

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 2018-07-09
    • 2016-06-06
    • 2020-02-16
    • 2019-03-06
    • 1970-01-01
    相关资源
    最近更新 更多