Is it possible to create multiple functions and calling them in one .m file?
4 次查看(过去 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 中查找有关 Data Type Identification 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!