How do I call a function from the command window

49 views (last 30 days)
myEquation(2)
function myEquation (x)
a = 0.4361836;
b = 0.1201676;
c = 0.937298;
r = exp(-0.5*(x^2))/(2*pi) ;
t = 1/(1+(0.3326*x)) ;
phi = 0.5 - r*((a*t)-(b*(t^2))+(c*(t^3))) ;
fprintf('The value of Φ(x) is: %i', phi)
fprintf('\n')
end
I have this code, and it works properly, however, I need a way to be able to call it from the command window. The line myEquation(2) auto inputs the value as 2, but I need to be able to enter other values without editing the code. Should I use an input prompt to prompt the user for a value of x to run my equation on?
  1 Comment
Stephen23
Stephen23 on 9 Feb 2024
"How do I call a function from the command window"
Very easily by making the file a function and not a script:
I.e. get rid of the line myEquation(2)
"Should I use an input prompt to prompt the user for a value of x to run my equation on?"
Ugh, no. Beginners love using INPUT prompts for eveything,and then have to unlearn that when they realize how much of an impedance INPUT is to writing expandable, testable, efficient code. Best avoided. Just write a function.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 9 Feb 2024
xval = input('enter x: ');
myEquation(xval)
function myEquation (x)
a = 0.4361836;
b = 0.1201676;
c = 0.937298;
r = exp(-0.5*(x^2))/(2*pi) ;
t = 1/(1+(0.3326*x)) ;
phi = 0.5 - r*((a*t)-(b*(t^2))+(c*(t^3))) ;
fprintf('The value of Φ(x) is: %i', phi)
fprintf('\n')
end

More Answers (1)

Steven Lord
Steven Lord on 9 Feb 2024
What you have right now is a script file with a function defined inside it. Functions inside script files are not directly accessible outside the script file.
Two potential options:
  1. Erase that first line in the file, to make the new first line the one with the function keyword. This makes the file a function file rather than a script file, and the first (main) function in a function file is directly accessible outside its file.
  2. Add a line that defines a function handle to the function and stores that function handle in a variable. If that function handle is created inside the script file, you will be able to call the function using the function handle. For example, I created a script file, ran it, and called the function via the function handle.
>> dbtype script2080121.m
1 fh = @fun2080121;
2 disp('Hello world!')
3
4 function z = fun2080121(x, y)
5 z = x+y;
6 end
>> script2080121
Hello world!
>> fh(3, 5)
ans =
8

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!