Matlab Bisection Algorithm code

13 ビュー (過去 30 日間)
Aaron Millan
Aaron Millan 2021 年 2 月 24 日
コメント済み: Aaron Millan 2021 年 2 月 24 日
% I'm trying to create a proper bisection code, and would like some advice on whether this code will...
%run properly. I am not sure how to test it, since every time I write a function on the
%command window, it tells me "x" is an unrecognized variable
function[r,resarray] = bisect(f,a,b,tol,N)
%f is my anonymous function, a and b are my guesses for where the root
%might be, tol if the tolerance(in this case 10^-6) and N is the
%maximum number of iterations
f = f(a);
k = 1;
while (k<= N && abs(f)>tol)
c = 0.5*(a+b);
f = f(c);
if f *f(a) <0
b = c;
else
a = c;
end
k = k+1;
end
r = c;
end
  2 件のコメント
Steven Lord
Steven Lord 2021 年 2 月 24 日
Can you show us how you're trying to call it and the full and exact text of any warning and/or error messages you receive?
I'm guessing you're doing this as part of a homework assignment. Does your textbook have any worked examples that you can try to run using your code to check that you receive the same results?
Nowhere do you assign a value to resarray so if you ever call your function with two outputs it will error.
Aaron Millan
Aaron Millan 2021 年 2 月 24 日
Hello! This is how I am attempting to call the function
bisect(sin(x),pi/2,1.5*pi,10^-6,100)
And this is the error message:
Unrecognized function or variable 'x'.

サインインしてコメントする。

採用された回答

Steven Lord
Steven Lord 2021 年 2 月 24 日
This
bisect(sin(x),pi/2,1.5*pi,10^-6,100)
attempts to call the sin function with the contents of the variable x as input and use whatever that function call returns as the first input to your bisect function. From that error message x doesn't exist and so MATLAB can't evaluate that function call, but even if it did exist the output likely would be a numeric array (if x was a numeric array.)
You want to give bisect a function it can call with inputs of its choice, and for that the easy thing to do is to pass an anonymous function or a regular function handle.
bisect(@(x) sin(x), pi/2,1.5*pi,10^-6,100)
bisect(@sin, pi/2,1.5*pi,10^-6,100)
What's an example where you might want to call a function and pass whatever it returns to bisect? One possible scenario is the "bind pattern", a function that returns a function handle.
bindK = @(k) @(x) x.^k; % This function handle creates and returns a function handle
f = bindK(2) % a function handle that computes x.^2
g = bindK(pi) % computes x.^pi
bisect(bindK(3), ...) % Use bisect on essentially @(x) x.^3
  1 件のコメント
Aaron Millan
Aaron Millan 2021 年 2 月 24 日
What a helpful answer! Thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by