running m file from command window

7 次查看(过去 30 天)
Rao
Rao 2012-8-5
i have this code for bisection method to calculate smallest root
% if true
function[x,e]=MyBisect(f,a,b,n)
%Does n iterations of the bisection method for a function f.
%Inputs f--Inline function
% a,b--Left and Right edges of interval
% n-- no.of bisections to do
%Outputs x--estimated solution of f(x)=0
% e--An upper bound on error
format long
c=f(a);d=f(b);
if c*d>0.0
error('Function has same signs')
end
disp(' x y')
for i=1:n
x=(a+b)/2;
y=f(x);
disp([ x y])
if y==0.0
e=0;
break
end
if c*y<0
b=x;
else
a=x;
end
e=(b-a/2); % code
endcode
end
i dont know how to run it from command window
f is equation of which to find the root eg(x-3-cosx)
a and b value is 1 and 2 resp
n no of iterations

回答(1 个)

Wayne King
Wayne King 2012-8-5
编辑:Wayne King 2012-8-5
Just save your function MyBisect.m in a folder that either already is on the Matlab path, or save it in a folder, and then add that folder to the Matlab path with
>>addpath 'path/to/folder'
or use pathtool
For example, assume that you are using Windows and that you create a folder called mfiles. Save MyBisect.m in that folder and then enter
>>addpath 'c:\mfiles'
After that command executes, you should be able to enter
>>which MyBisect
and see that Matlab recognizes the path to the Matlab program.
Now you should be able to call it from the command line with the syntax:
[x,e]=MyBisect(f,a,b,n)

类别

Help CenterFile Exchange 中查找有关 Language Fundamentals 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by