Undefined function error message

1 view (last 30 days)
Hi guys, I am using Live Editor and I want to write a function and then have that function automatically be called when I hit run all. Before having the function automatically be called when I run the script, I have tried to just call the function from the command window, but it does not work. It says that the function is undefined.
Here is my code:
clear all;
function myfun(initialspeed, initialangle, Nmaxstep)
%Fundamental Constants
m_e = 9.10938188E-31; %Mass of positron
q_e = 1.60217646E-19; %Charge of positron
qbym = q_e/m_e; %Charge to mass ration of positron
%Input Fields
Ey = 10E5 %Y component of electric field
Ex = 0 %X component of electrin field
Bz = 1 %Z component of magnetic field
%Initial conditions
x1 = 0; y1 = 0; %having electron start at the origin for simplicity
r1 = [x1,y1] %initial position vector of electron
theta1 = initialangle*pi/180; % converting the direction from degrees
to radians
v1 = [initialspeed*cos(theta1), initialspeed*sin(theta1)] % initial
velocity
r = r1; v = v1;
%Time step for loop
deltat = (qbym*Bz)^-1/1000; %qbym*Bz is the cyclotron frequency
%Loop to calculate trajectory
for istep=1:Nmaxstep
%Current position
xorbit(istep)=r(1);
yorbit(istep) = r(2);
t=(istep-1)*deltat;
%acceleration at this position
accel(1)=qbym*(Ex+v(2)*Bz);
accel(2)=qbym*(Ey-v(1)*Bz);
%using Euler's method to calculate new state
r = r + v*deltat;
v = v + accel*deltat;
end
%Plotting trajectory
clf; figure(gcf);
plot(xorbit,yorbit);
title('Positron trajectory')
xlabel('X (meters)')
ylabel('Y (meters)')
end
end
When I try to call my function myfun(#,#,#), I get an error saying that the function is undefined. Why is this not working?

Accepted Answer

Walter Roberson
Walter Roberson on 27 Oct 2017
Edited: Walter Roberson on 13 Apr 2018
When you define a function within a script, the function cannot be called from outside the script.
When you define a function inside a script, you should imagine that at the top of the script you had put in "function" with the name of your file, at least for the purposes of locating routines.
... But putting a "clear all" in a script is not a good idea: it tells MATLAB to scrub everything except existing graphics objects. "clear all" could, in theory, even cause MATLAB to lose track of which script or function it was executing, because "clear all" is the programming equivalent of Wile E. Coyote blowing up the piece of rock he is standing on.

More Answers (0)

Categories

Find more on Biomedical Imaging in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!