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!