在循环

时间:2018-01-31 18:55:51

标签: matlab function for-loop function-parameter

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

我创建了一个函数:

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.

我该如何解决?谢谢

1 个答案:

答案 0 :(得分:0)

我想我有一个答案。根据{{​​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