Calling functions from different scripts

1 view (last 30 days)
Arnav
Arnav on 25 Apr 2014
Commented: dpb on 26 Apr 2014
%func.m function f=transs(alpha) f=exp(-alpha)+alpha-1 end
i wrote this function in a script,but when i try calling it in another script using transs(theta),it keeps giving me an error saying alpha is not defined, i called func.m by writing func; in the code,why am i getting this error. func.m works through the command window though.The following is the second script i wrote calling func.m.
init1; func; theta=1:0.5:20 H11=zeros(1,numel(theta)); H12=zeros(1,numel(theta)); H21=zeros(1,numel(theta)); H22=zeros(1,numel(theta));
data= zeros(1,numel(theta)); for i=1:numel(theta) H11(i)=(theta(i)^2)/2-transs(theta(i)); H12(i)=(theta(i)^2)/2-transs(theta(i)); H21(i)=(theta(i)^2)/(2*epsilon1)-(epsilon1*transs(theta(i)/epsilon1)); H22(i)=(theta(i)^2)/(2*epsilon2)-(epsilon2*transs(theta(i)/epsilon2)); end

Accepted Answer

dpb
dpb on 25 Apr 2014
Firstly, format your code so it's legible...use two blanks in front of first code line in a new paragraph. Keep at it until it looks right in the code window....
The reason alpha is undefined in the second invocation is that you didn't pass any arguments when you called func as shown below...
nit1;
func; % where's the required argument???
...
Also, what's the point in calling the function if you don't provide any return variable? There's no effect in the calling routine of having done so without it.
Also, it's very bad form (and bound to be confusing at best) to not name the m-file the same as the function name. What are you going to do when you want a second function and you've already used func as a name? Name the m-file in the case of your function transs.m and then call it as
fval=transs(inputalpha);
  4 Comments
Arnav
Arnav on 25 Apr 2014
actually never mind i got it.thank you.
dpb
dpb on 26 Apr 2014
...formatting gets a little wonky when i copy it straight from the script
Yeah, the text control defaults TMW uses are just a very poor choice for a coding forum -- it should default to fixed-width font and no wordwrap instead and then let folks format text if so choose instead of the obverse where have to go out of way to write legible code. I'd guess 80% or more of initial submissions are not formatted well--it's a real waste of time/effort.
Anyway, complai^h^h^h^h^h^h^hsuggestions aside -- if you paste code, just then insert two blank spaces in front of the first line and magic will happen. You'll then only need to repeat that for lines following blanks where the control loses it's way again...

Sign in to comment.

More Answers (0)

Categories

Find more on Environment and Settings 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!