Is it possible to create multiple functions and calling them in one .m file?
1 回表示 (過去 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!