Introduction

Matlab Logo 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.

msgbox GUI

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.

    error msgbox

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

    warning msgbox

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

    help msgbox

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.

    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.

    GUIDE Screen

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

    GUI skeleton

  5. Click on the mfile icon icon on the GUI figure to bring up the accompanying .m file.

  6. Now, we want to add the following code to edit1_Callback.

    input = get(handles.edit1,'String'); %get the input from the edit text field
    input = str2num(input); %change from string to number
     
    if isempty(input) %if the input is not a number
     
        %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.';
     
        %notice that msgboxText is a Cell array!
     
        %this command creates the actual message box
        msgbox(msgboxText,'Input not a number', 'help');
     
    elseif input == 100 %if the input is exactly 100
        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');
     
    elseif input < 0 || input > 100 %if the input is less than 0 or greater than 100
        msgboxText{1} =  'You have chosen a value outside the range of 0-100!';
        msgbox(msgboxText,'Input not allowed', 'error');
    end
  7. And that’s 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. It’s purely a matter of preference. For example:

msgbox('hello world', 'hello world','error');
 
%an equivalent command
errordlg('hello world','hello world')

Download the Source Files

You can download the source files here.