Combining multiple functions within one script

I have three functions I would like to put into one script. What would be the correct steps to do so. here are the following functions I have written.
function [] = gravitationalForce(m1,m2,d)
%{m1 = mass 1, m2 = mass 2, d = distance%}
G = 6.672 * 10^11;
syms F
F = (G*m1*m2/(d^2));
display(F)
end
function [] = velocityCalc(u,a,s)
%{u = velocity,a = acceleration,s = distance traveled%}
disp('V^2 =')
v = (u^2 + (2*a*s));
disp(v)
end
function [] = distanceTraveled(u,a,t)
%{u = velocity,a = acceleration,t = time%}
syms s
s = (u*t)+1/2*a*t^2;
display(s)
end

6 comentarios

Brooks Nelson
Brooks Nelson el 19 de Feb. de 2017
Editada: Walter Roberson el 20 de Feb. de 2017
I figured it out. If anyone was wandering I created another function physics with an end after all the full functions were inputed. This allowed me to call the function physics. I then can call each function within the function for an answer. Probably not the best way to do it but it worked for now.
function physics
function [] = gravitationalForce(m1,m2,d)
%{ m1 = mass 1,m2 = mass 2,d = distance%}
G = 6.672 * 10^11;
syms F
F = (G*m1*m2/(d^2));
display(F)
end
function [] = velocityCalc(u,a,s)
%{u = velocity,a = acceleration,s = distance traveled,%}
disp('V^2 =')
v = (u^2 + (2*a*s));
disp(v)
end
function [] = distanceTraveled(u,a,t)
%{u = velocity,a = acceleration,t = time%}
syms s
s = (u*t)+1/2*a*t^2;
display(s)
end
end
Learner
Learner el 15 de En. de 2020
looks good but how to call a sub function within physcics function
The only ways to call a subfunction that is defined inside another function are:
1. Somehow obtain a handle to the subfunction. For example calling the wrapper function "physics" could return handles to the subfunctions; or
2. Have the wrapper function be a "switchyard" where you pass in information about which subfunction you want to call and the wrapper function calls it on your behalf. For example
function varargout = physics(request, varargin)
switch request
case 'grav'
[varargout{1:nargout}] = GravitationalForce(varargin{:}) ;
end
Invoke with
physics('grav', m1, m2, d)
Kazi Newaz
Kazi Newaz el 3 de Feb. de 2022
Editada: Kazi Newaz el 3 de Feb. de 2022
I get the error Undefined function or variable. What am I doing wrong?
function varargout = addcomp(request, varargin)
function outc=addcomp1(z1,z2)
realpart=real(z1)+real(z2);
imagpart=imag(z1)+imag(z2);
outc=realpart+imagpart*1i;
end
function outc=addcomp2(z1,z2)
outc=z1+z2;
end
switch request
case 'addcomp1'
[varargout{1:nargout}]=addcomp1(varargin{:});
case 'addcomp2'
[varargout{1:nargout}]=addcomp2(varargin{:});
end
end
How are you invoking the function, and what is the complete error message?
Kazi Newaz
Kazi Newaz el 3 de Feb. de 2022
extremely sorry to have bothered you, it was an issue with me not having the path set up right, now it is working, thank you so much for the solution

Iniciar sesión para comentar.

Respuestas (4)

Mohammad Askari
Mohammad Askari el 30 de Jun. de 2018
Editada: Mohammad Askari el 18 de Nov. de 2019
Another approach is to create a class with static methods with all your sub-functions. Save the following code as ALLFUNCS.m
classdef ALLFUNCS
methods(Static)
function result = SumElements(a,b,c)
result = a + b + c;
end
function [prod,div] = MultiplyDivide(v1,v2,v3)
prod = v1 * v2 * v3;
div = v1 / v2 / v3;
end
end
end
Then you can simply call the sub-functions like this:
s = ALLFUNCS.SumElements(3,4,5);
[p,d] = ALLFUNCS.MultiplyDivide(8,3,5);

2 comentarios

leanne dong
leanne dong el 2 de Abr. de 2020
this method does not seem to work for case where a function depends on the previous one.
Any suggestions?
Mohammad Askari
Mohammad Askari el 3 de Abr. de 2020
Editada: Mohammad Askari el 31 de Oct. de 2021
@leanne dong, it actually does. In the example below, the first function calls the other one. Is this what you are looking for?
classdef ALLFUNCS
methods(Static)
function result = SumElements(a,b,c)
result = a + b + c;
string = ALLFUNCS.IsGreaterThanZero(result);
disp(['the answer is greater than zero: ',string]);
end
function str = IsGreaterThanZero(value)
if value > 0
str = 'true';
else
str = 'false';
end
end
end
end

Iniciar sesión para comentar.

Anders Bergåker
Anders Bergåker el 26 de Oct. de 2017
Well, I find this limitation incredibly annoying so I use a workaround with the sfunc command. The first function takes the function you actually want to call as an argument. I've found this workaround ages ago, it might have some drawbacks I'm unaware of since I'm not an Matlab expert.
Put all this code in an .m file, eg. myLib.m which then will act as a function library. The call to use a specific function would then be:
myLib('distanceTraveled', u, a, t)
It work fine with returnvalues as well. Examaple of myLib.m:
function varargout = sfunc(varargin)
[varargout{1:nargout}] = feval(varargin{:});
end
function [] = gravitationalForce(m1,m2,d)
...
end
function [] = velocityCalc(u,a,s)
...
end
function [] = distanceTraveled(u,a,t)
...
end

6 comentarios

Rahul Gupta
Rahul Gupta el 13 de Abr. de 2018
If I use this method. do I need to do any configuration for myLib.m file like import or adding path?
Walter Roberson
Walter Roberson el 21 de Abr. de 2018
Like everything for MATLAB it would have to be on your MATLAB path, but you would not need to import
Mohammad Askari
Mohammad Askari el 30 de Jun. de 2018
Nice idea! The only downside is that it creates a false warning ("this function might be unused") for every individual sub-function. Do you have a workaround for this ?
"false warning"
Add the line
%#ok<*DEFNU>
to mylib.m
Marcel
Marcel el 15 de Mayo de 2024
Works fantastic and is elegant. Thanks!
You could also comment out the function(s) with %{ and %}.
For example:
%{
function out = MyFunction(in)
out = 2 * in;
end
%}

Iniciar sesión para comentar.

Image Analyst
Image Analyst el 19 de Feb. de 2017

1 voto

You can do that but velocityCalc() and distanceTraveled() would only be available/seen to functions within the same file. If they need to be used by other m-files, you'd have to have them in separate files, unless they were a class. I've done this so I know it works. If you had a class with those functions in it, then any file could call any of those functions as a static method of the class.
John D'Errico
John D'Errico el 19 de Feb. de 2017
Editada: John D'Errico el 19 de Feb. de 2017

0 votos

If your goal is to use those function independently, then they need to be saved as separate m-files, NOT in one large file. While it would indeed be possible to do that in theory, you would need to learn a fair amount about function handles to do so. As well, you would need to call a main function, then having it return function handles for each sub-function that you might call in the future.
If you are somehow thinking of having an actual script that also has a mainline, but with functions defined within, that is not possible. Scripts cannot also contain function definitions, except for the case of function handles created in one line.
Simple save each function as an independent m-file.

1 comentario

Image Analyst
Image Analyst el 19 de Feb. de 2017
Starting with R2016b, you can have function(s) below a script all within the same m-file.

Iniciar sesión para comentar.

Categorías

Más información sobre Function Creation en Centro de ayuda y File Exchange.

Productos

Preguntada:

el 19 de Feb. de 2017

Comentada:

el 16 de Mayo de 2024

Community Treasure Hunt

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

Start Hunting!

Translated by