.
5. After running this GUI ( Click the green button), M-file for your GUI calculator will be generated. For the time being we are only concerned with the callbacks. As seen above , we have got 4 push buttons, 2 input fields and one output field. We will proceed such that we will save the inputs entered by the user in some variable. Thereafter we will add, subtract, multiply, divide depending on what user wants. Usually we use get function to take input and set to display the output. How to view callbacks? See below :-
6. Following portion of M-file would be in picture :-
7. Lets come to the coding of individual callbacks in our GUI calculator. First of all we know that the output field (where the answer will be displayed) does not need any callback coding. So we are left with only 4 push buttons and 2 input fields. Lets talk about each individually :- (Same method is adapted to view the callbacks in each case)
Ist No Callback
Insert the following code inside the Ist Number callback. Also see the commented lines to grasp the "critical points"
num1= str2double(get(hObject, 'String'));
% get is used to get the data from the input field field
% str2num; because input is always taken as string
% final value is stored in num 1
handles.calc.x=num1;
% not NEEDED. will work without handles.calc.x.num1. % handles.calc.x ; .calc.x may be replaced as desired (abc.z) but through
% the M-file use the same "calc" like handles.calc.y, handles.calc.z etc
% necessarily be needed if used in some other function
guidata(hObject,handles);
% to update the field
2nd No Callback
Similarly for the second input, enter the following inside the callback function
num2= str2double(get(hObject, 'String'));
handles.calc.y=num2;
% not NEEDED. will work without handles.calc.x.num1.
guidata(hObject,handles);
See also the comments made in Ist No Callback
Operands Callback
Additon:
add=handles.calc.x+handles.calc.y;
% adding the two numbers (could not add if we had not used handles.calc.y etc in Ist % and 2nd no cal l back
set(handles.ans , 'String', handles.calc.add);
% This is used to display the output (i-e additon)
% handles.ans ; ans is the tag for output field (may be viewed and changed in
% inspector)
Subtraction:
sub=handles.calc.x-handles.calc.y;
set(handles.ans , 'String', sub);
Multiplication
mul=handles.calc.x*handles.calc.y;
set(handles.ans , 'String', mul);
Division
div=handles.calc.x*handles.calc.y;
set(handles.ans , 'String', div);
Congratulations! Your Matlab GUI calculator is ready
Now you are just one step ahead to see your calculator working . Click the green button or press F5. Your first working GUI calculator is ready. You can open it again by typing in calc (in my case) or with whatever named you have saved the M-file. The calculator looks like :-