how to call this function in another script?

1 回表示 (過去 30 日間)
Mohammed AlQahtani
Mohammed AlQahtani 2022 年 2 月 9 日
回答済み: Nivedita 2023 年 11 月 14 日
function M=bisFor(f, a, b, ~)
M=ceil((log10(b-a)/TOL)/log10(2));
FA=f(a);
value=(1:M);
for i=value
p=a+(b-a)/2;
FP=f(p);
if sign(FA)==sign(FP)
a=p;
FA=FP;
else
b=p;
end
end
p=a+(b-a)/2;
end
  2 件のコメント
Abolfazl Chaman Motlagh
Abolfazl Chaman Motlagh 2022 年 2 月 9 日
the error is in mmmm.m file. you should show us what is in line 7 of that.
Jan
Jan 2022 年 2 月 9 日
編集済み: Jan 2022 年 2 月 9 日
Just a hint:
value=(1:M);
for i=value
This is much slower than:
for i = 1:M
What is the purpose of defining a 4th ignored input?
function M=bisFor(f, a, b, ~)
% ^ ??
On the other hand, what is "TOL"? Do you want to provide this as 4th input?

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

回答 (1 件)

Nivedita
Nivedita 2023 年 11 月 14 日
I understand that you want to call the "bisFor" function in another script. To call this function in another script, you just need to make sure the function is in your MATLAB path. Then, you can call it just like any other function.
Here's an example of how you can call this function:
% Define the function you want to find the root of
f = @(x) x^2 - 2;
% Define the interval [a, b]
a = 1;
b = 2;
% Define the tolerance
TOL = 1e-5;
% Call the bisFor function
M = bisFor(f, a, b, TOL);
% Display the result
disp(M);
In this script, we first define the function "f" using a function handle. This function is "x^2 - 2", which has a root at "sqrt(2)". Then we define the interval [a, b] where we want to find the root, and the tolerance "TOL" for the bisection method. Finally, we call the "bisFor" function with these parameters and display the result.
Please replace the function "f", the interval [a, b], and the tolerance "TOL" with your own values as needed.
For more information on function handles, you can refer to the following documentation link:
I hope this helped!
Regards,
Nivedita.

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by