Call different functions inside a function
3 次查看(过去 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
0 个评论
回答(2 个)
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
%% 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
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
%% 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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!