Is it possible to create multiple functions and calling them in one .m file?
조회 수: 6 (최근 30일)
이전 댓글 표시
I have a question about calling a function in Gui. Here is an example of my code:
function pushbutton1_Callback(hObject, eventdata, handles)
ABC = handles.Murthy(result); %%????? This line
%button implementation
function maxmax = Murthy (result)
%Murthy implementation
The function Murthy also contains "axes(handles.axes1);" etc. How to call function Murthy without deleting gui control codes (like "axes(handles.axes1)" etc) from it? Thanks in advance!
댓글 수: 4
Walter Roberson
2013년 8월 27일
편집: Walter Roberson
2013년 8월 27일
ABC = handles.Murthy(result);
is not going to work because you do not have "result" defined.
Is Murthy going to return the name of an axis ? Is it going to return an axes object that you then want placed under a figure determined by pushbutton1_Callback ??
채택된 답변
Iain
2013년 8월 28일
편집: Iain
2013년 8월 28일
Generically, this is the process:
function whee = whatevs(a,b,c) %1st line of m file
whee = alpha(a) + beta(b) + gamma(c);
end
function a = alpha(x) %still in the whatevs.m
a = x.^2;
end
function b = beta(x) %still in the whatevs.m
b = 2.^x;
end
function c = gamma(x) %still in the whatevs.m
c = x^x;
end
You can also "nest" functions: eg, gamma could be:
function c = gamma(x) %still in the whatevs.m
c = banana^x;
function b = banana
b = randn*5;
end
end
댓글 수: 2
Sara
2017년 9월 19일
Lain, how do you call function b or c in a separate script this way?
I know it is possible to make separate .m files for each function and call them that way. I currently have a script that calls three functions, which are all each their own .m file. I am trying to simplify my code some, so if you can do it the way you described, this would help.
Walter Roberson
2017년 9월 19일
To be able to call a function from outside of the file it is stored in:
1) the function can be in its own file named the same as the function (like you have now); or
2) somehow the calling function has to have been given a handle to the function to be called. For example,
function fh = switchyard(which_function)
switch lower(which_function)
case 'add': fh = @add_all_the_things;
case 'ghoti': fh = @go_fish;
otherwise:
error('not a known function for switchyard');
end
end
function [a, b, c] = add_all_the_things(....)
...
end
function d = go_fish(....)
...
end
Then another function could say,
fish = switchyard('ghoti');
r = fish( randi(13) );
The switchyard function would return a handle to the go_fish function stored in switchyard.m and then once the calling function has that handle, it can invoke it.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Dynamic System Models에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!