You are on page 1of 4

Matlab GUI - Using msgbox to Create a Better GUI 18 Feb 2008 Quan Quach 20 comments 5,346 views Introduction

The msgbox command in Matlab can provide valuable information to the user of your GUI. It can warn the user, inform the user of an error, and also provide help. In this example, we will use a GUI (shown below) consisting of a simple edit text component.

The GUI takes in inputs between 0 to 100.

If the user tries to input a numerical value that is not within 0-100, then the GUI will spit out an error message.

If you user tries to set the value to 100, the user will give off a warning message.

If you try to input something that is not a number, the user will get a help message.

The Example 1. First, download the GUI skeleton here. Unzip the files and place them wherever you please. 2. Now, type guide at the command prompt.

3. Choose to open the sample GUI by clicking on Open Existing GUI. Click on Browse to locate where you saved the GUI files.

4. Here is what the GUI should look like when you open it:

5. Click on the icon on the GUI figure to bring up the accompanying .m file. 6. Now, we want to add the following code to edit1_Callback. 7. input = get(handles.edit1,'String'); %get the input from the edit text field 8. input = str2num(input); %change from string to number 9. 10.if isempty(input) %if the input is not a number 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. %this command creates the actual message box msgbox(msgboxText,'Input not a number', 'help'); %notice that msgboxText is a Cell array! %this is the first line of the msgbox msgboxText{1} = 'You have tried to input something that is NOT a number.'; %this is the second line msgboxText{2} = 'Try an input between 0 and 100 instead.';

21. 22.elseif input == 100 %if the input is exactly 100 23. 24. 25. 26. 27.elseif input < 0 || input > 100 %if the input is less than 0 or greater than 100 28. 29. end 30.And thats it! Run the GUI to make sure that it does what you expect it too. Other tips The msgbox command can be replaced with the errordlg, warndlg, and helpdlg commands. Its purely a matter of preference. For example: msgbox('hello world', 'hello world','error'); msgboxText{1} = 'You have chosen a value outside the range of 0-100!'; msgbox(msgboxText,'Input not allowed', 'error'); msgboxText{1} = 'You have chosen the highest possible input!'; msgboxText{2} = 'You cannot go any higher than this or it will result in an error.'; msgbox(msgboxText,'Maximum input chosen', 'warn');

%an equivalent command errordlg('hello world','hello world') Download the Source Files