Matlab Bisection Algorithm code

조회 수: 11 (최근 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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by