Call different functions inside a function

2 vues (au cours des 30 derniers jours)
Gonzalo Guerrero
Gonzalo Guerrero le 7 Nov 2022
HI there,
I am trying something I haven't done before, but I would like to learn how to do it, so I get a bit more experiences in it.
So, I have scripts that are very long, with few functions in it, and then I got other scripts that have functions that could help in different cases. So, I have decided that I want to create small functions that do small things, then create a main function that call those functions and import the data for the next function to work.
script1.m
function w=script1(a)
w=x
end
script2.m
function s=script2(w)
s=m
end
script3.m
function g=script3(w)
g=f
end
From those I would like to create a main function
mainscript.m
function mainscript()
script1
(gives back w)
script2
(gives back s)
script3.m
(gives back g)
end
any help will be appreciated!
Thank you,
Gonzalo

Réponses (2)

Davide Masiello
Davide Masiello le 7 Nov 2022
Modifié(e) : Davide Masiello le 7 Nov 2022
The way you have explained it in your question is already correct.
See the example below.
%% Main script
mainfunction
ans = 4
ans = 3
ans = 1.4142
%% Main function
function mainfunction()
myfun1(2)
myfun2(2)
myfun3(2)
end
%% Function 1 script
function out = myfun1(x)
out = x.^2;
end
%% Function 2 script
function out = myfun2(x)
out = x+1;
end
%% Function 3 script
function out = myfun3(x)
out = sqrt(x);
end
  1 commentaire
Steven Lord
Steven Lord le 7 Nov 2022
If you want to use the output from myfun1, myfun2, myfun3 you need to call them with output arguments and pass those output arguments into the next function.
%% Main script
outputFromMainFunction = mainfunction
a = 4
banana = 5
c123 = 2.2361
outputFromMainFunction = 2.2361
%% Main function
function c123 = mainfunction()
a = myfun1(2)
Because I've omitted the semicolon at the end of these lines, MATLAB will print each output argument as it computes them. End the lines where you call myfun1, myfun2, and myfun3 with a semicolon if you want to suppress this display.
banana = myfun2(a)
c123 = myfun3(banana)
end
%% Function 1 script
function out = myfun1(x)
out = x.^2;
end
%% Function 2 script
function out = myfun2(x)
out = x+1;
end
%% Function 3 script
function out = myfun3(x)
out = sqrt(x);
end

Connectez-vous pour commenter.


Gonzalo Guerrero
Gonzalo Guerrero le 10 Nov 2022
Thank you guys!
I think i got the hang of it now! :D
cheers,
Gonz

Catégories

En savoir plus sur Performance and Memory dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by