Call different functions inside a function

2 次查看(过去 30 天)
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

回答(2 个)

Davide Masiello
Davide Masiello 2022-11-7
编辑:Davide Masiello 2022-11-7
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 个评论
Steven Lord
Steven Lord 2022-11-7
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

请先登录,再进行评论。


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

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by