Call a function inside a script from another script

118 visualizaciones (últimos 30 días)
Leonard
Leonard el 4 de Sept. de 2014
Comentada: Geoff Hayes el 6 de Sept. de 2014
Hey people, I have a short question and couldn't find an answer to that:
I have a script with several functions and I want to call a particular function inside this script, but from another script.
If that sounds confusing here a quick example:
m-File "AllFunctions"
function a
a = 1;
function b
b = 1;
m-File "Main"
>>> Now I want to get access to function a from the "AllFunctions"-m-File.
Would be great if you can help me or if you recommend a better way handling such a problem.
Thanks!
Leo

Respuesta aceptada

Geoff Hayes
Geoff Hayes el 4 de Sept. de 2014
Leonard - I'm pretty sure that you can't do that. If your m-file is named AllFunctions.m, then either it is a script that you can run or it is a function which has the same name as the file which you can call (passing in arguments, getting a result, etc.), but you cannot access any other function that has been defined in that file.
If I wanted to do something like what you suggest, then I would create a class with static methods. I've done this for C++ when I wanted a class that had some common algorithms, so there is no reason why you can't do something similar in MATLAB. Suppose the following is your class definition (saved in a file called AllFunctions.m)
classdef AllFunctions
methods(Static)
function [x] = a
x = 1;
end
function [x] = b
x = 2;
end
function [x] = c(var)
x = 3*var;
end
end
end
There isn't all that much to it: the class definition with a section for static methods, in this case, for the functions a, b, and c. In the Command Window, I can invoke each function as
>> AllFunctions.a
ans =
1
>> AllFunctions.b
ans =
2
>> AllFunctions.c(27)
ans =
81
So using a class, you should be able to do something along the lines of what you want.
  3 comentarios
Leonard
Leonard el 6 de Sept. de 2014
Implemented it today and it works awesome! Thank you so much! This is great :)
Geoff Hayes
Geoff Hayes el 6 de Sept. de 2014
Glad it worked out!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Software Development Tools en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by