Reputation: 237
I am trying to create a button in GUI matlab and call a function when it is pressed. This code it is not working. I have also tried to use these values in the last argument of uicontrol: fnHi, 'fnHi', 'fnHi();'
The code is:
function [] = testui()
function fnHi()
fprintf('hi');
end
fnHiHandler = @fnHi;
fnHiHandler(); fnHi();
figure();
uicontrol('Style', 'pushbutton', 'string', 'Hi', 'callback', fnHiHandler);
end
The output is:
testui()
hihiUndefined function or variable 'fnHiHandler'.
Error while evaluating uicontrol Callback
So the function works since it is called twice but when I press the button it crashes. I dont want to use more than one file. Thank you.
Upvotes: 1
Views: 728
Reputation: 237
Ok, I found the answer. The problem is that fnHi should receive two arguments, otherwise it will crash saying that are too many input arguments. So this code works:
function [] = testui()
function fnHi(source,eventdata)
fprintf('hi');
end
fnHiHandler = @fnHi;
fnHiHandler(); fnHi();
figure();
uicontrol('Style', 'pushbutton', 'string', 'Hi', 'callback', fnHiHandler);
end
Upvotes: 1