Selecting on function from an array of anonymous functions
11 次查看(过去 30 天)
显示 更早的评论
I have an array of 3 anonymous functions where the user is asked to select one of the three functions. It choses which function with a number of variables that passes it to the function bisect that will approximate the roots of the function. If I type the actual equation and the variables into the function bisect it works. If I pass it through a seperate .m file as I am doing here, it gives me the error:
Undefined operator '^' for input arguments of type 'cell'.
Error in Q2a>@(x)x^3-5*cos(x/2)
Error in bisect (line 15)
fa = f(a);
Error in Q2a (line 15)
bisect(f, x0(1), x1(1), nmax, eps, printflag)
where Q2a is the .m file with the folling code. How can I make this work?
eq_array = {@(x)x.^3-5*cos(x/2),@(x)tan(x/2)-x,@(x)43*x*log(x)-2*x.^2};
x0={0.5 1 75};
x1={4 3 125};
eps={0.5e-7 0.5e-9 0.5e-7};
prompt=('Which equation do you want to evalute? (1,2 or 3): ');
eq=input(prompt);
f=eq_array(eq);
x0=x0_array(eq);
x1=x1_array(eq);
nmax=40;
eps=0.5e-7;
prinflag=1;
bisect(f, x0, x1, nmax, eps, printflag)
0 个评论
采纳的回答
Steven Lord
2019-2-6
Indexing into a cell array using parentheses returns one or more elements of the cell array. The result is itself a cell array.
Indexing into a cell array using curly braces returns the contents inside one or more elements of the cell array.
Compare:
C = {1, 2, 3}
paren = C(2) % Still a cell array
curly = C{2} % Double array
whos C paren curly
You want to extract the contents inside the cell array and pass those contents into your function, so use curly braces not parentheses.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 String Parsing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!