Call different functions inside a function

조회 수: 4 (최근 30일)
Gonzalo Guerrero
Gonzalo Guerrero 2022년 11월 7일
답변: Gonzalo Guerrero 2022년 11월 10일
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에서 Performance and Memory에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by